EF Core learning Code First, efcorecodefirst
The following describes how to learn EF Core Code First through an instance, that is, to generate a database from the model through EF Core migration.
This example uses the EntityFrameworkCore SQLite database for introduction. You can also seamlessly switch to other databases.
Currently, EF Core supports the following databases:
- Microsoft SQL Server
- SQLite
- Postgres (Npgsql)
- SQL Server Compact Edition
- InMemory (for testing purposes)
- MySQL
- IBM DB2
1. Create a project
Create a project, select. NET Core, select ASP. NET Core Web Application (. NET Core), and name it EFCoreDemo, as shown in.
Click OK. The select template dialog box is displayed. Select a Web application template and set "authentication" to "no authentication", as shown in.
2. Reference Entity Framework Core
Install references under the NuGet command line:
Install-Package Microsoft.EntityFrameworkCore.Sqlite
You can also use the NuGet package to search for Microsoft. EntityFrameworkCore. Sqlite in the Manager for installation.
3. Create an object
Add a Models folder to the project, and then right-click the Models folder to create a class User. cs:
public class User { public int Id { get; set; } public string UserName { get; set; } public string Password { get; set; } }
Create another class DataContext. cs:
public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<User> Users { get; set; } }
4. Create a database
Open Startup. cs and add the following code in the ConfigureServices method:
public void ConfigureServices(IServiceCollection services) { var connection = "Filename=./efcoredemo.db"; services.AddDbContext<DataContext>(options => options.UseSqlite(connection)); // Add framework services. services.AddMvc(); }
Using Microsoft. EntityFrameworkCore is required;
After the configuration is completed, install and reference Microsoft. EntityFrameworkCore. Tools. Run the NuGet command line:
Install-Package Microsoft.EntityFrameworkCore.Tools
Create a database. Run the commands on the package management console to migrate and update the database.
Open the VS 2017 menu tool → NuGet Package Manager → package management console.
Enter Add-Migration MyFirstMigration for execution, and then enter Update-Database for execution. If Done is displayed, the database is successfully created.
To use the dotnet ef command, first open the EFCoreDemo. csproj file and add the following to the Project node:
<ItemGroup> <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" /> </ItemGroup>
If it is edited in VS, it will be automatically restored. Manual dotnet restore is required for external editing.
After restoration, you can use the dotnet ef command.
Enter dotnet ef migrations add MyFirstMigration in the command prompt, and then enter dotnet ef database update.
The prompt is displayed, so that we have created a database, as shown in. For more EF commands, enter dotnet ef-h.
5. project use
Right-click the Controllers folder and choose add> new item from the shortcut menu to create an MVC controller UserController:
UserController. cs
public class UserController : Controller { private DataContext _context; public UserController(DataContext context) { _context = context; } // GET: /<controller>/ public IActionResult Index() { return View(_context.Users.ToList()); } public IActionResult Register() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Register(User registeruser) { if (ModelState.IsValid) { _context.Users.Add(registeruser); _context.SaveChanges(); return RedirectToAction("Index"); } return View(registeruser); } }
You will notice that the controller needs DataContext as the constructor parameter. ASP. NET Core dependency injection injects DataContext to the Controller through constructor.
The Index action shows all users. The registered Register action user adds the user to the user table.
Add a User folder to the Views folder and add an Index view:
Index. cshtml
@ Model IEnumerable <EFCoreDemo. models. user >@{ ViewBag. title = "user ";} <table class = "table"> <tr> <th> Id </th> <th> User Name </th> </tr> @ foreach (var item in Model) {<tr> <td> @ Html. displayFor (modelItem => item. id) </td> <td> @ Html. displayFor (modelItem => item. userName) </td> </tr >}</table>
Next, add a Register view.
@ Model EFCoreDemo. models. user @ {ViewBag. title = "Add User ";} <form asp-controller = "User" asp-action = "Register" method = "post"> <div class = "form-group"> <label asp-for = "UserName "class =" col-md-2 control-label "> User Name: </label> <div class = "col-md-10"> <input class = "form-control" asp-for = "UserName"/> <span asp-validation-for = "UserName "class =" text-danger "> </span> </div> <label asp-for =" Password "class =" col-md-2 control-label "> Password: </label> <div class = "col-md-10"> <input class = "form-control" asp-for = "Password"/> <span asp-validation-for = "Password "class =" text-danger "> </span> </div> <div class =" col-md-offset-2 col-md-10 "> <input type =" submit "value =" save "class = "btn-default"/> </div> </form>
Select EFCoreDemo for debugging and start the program. Then, enter http: // localhost: 5000/User/Register in the address bar to access registration.
Enter user information in the registration area. After successful registration, you will be redirected to http: // localhost: 5000/User, as shown in.
This article is aboutASP. NET Core cross-platform development from getting started to practical use 6.2 Code FirstIs also an update of the previous blog post ASP. NET Core development-Entity Framework (EF) Core.
If you think this article is helpful to you, click"Recommendation", Thank you.