创造 a model class
我们必须在项目中创建一个models文件夹。之后,您可以按照以下给定步骤将模型类和上下文类添加到models文件夹下。
转到“模型”文件夹,右键单击“模型”文件夹,然后指向“添加”,然后单击“类”。您可以选择一个类并输入类名称作为UserContext,然后单击“添加”按钮。
同样,您可以在项目的“模型”文件夹下添加“用户”和“角色”类。
用户.cs
using System;
using System.Collections.Generic;
namespace ASP.NETCoreWithEFCore.Models
{
public 类 用户
{
public int UserId { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public List<Role> Roles { get; set; }
}
}
Role.cs
using System;
namespace ASP.NETCoreWithEFCore.Models
{
public 类 Role
{
public int RoleId { get; set; }
public RoleType RoleTyp { get; set; }
public int UserId { get; set; }
public 用户 User { get; set; }
}
public enum RoleType
{
Admin,
User
}
}
用户Context.cs
using System;
using Microsoft.EntityFrameworkCore;
namespace ASP.NETCoreWithEFCore.Models
{
public 类 用户Context:DbContext
{
public UserContext(DbContextOptions<用户Context> dbcontextoption)
:base(dbcontextoption)
{ }
public DbSet<用户> Users { get; set; }
public DbSet<Role> Roles { get; set; }
}
}
怎么样 to register our context class with dependency injection
您可以在启动类中详细了解如何通过运行应用程序启动的依赖项注入来注册上下文类。
- 转到解决方案资源管理器,打开Startup.cs类并添加以下名称空间并注册上下文类
启动文件
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ASP.NETCoreWithEFCore.Models;
using Microsoft.EntityFrameworkCore;
namespace ASP.NETCoreWithEFCore
{
public 类 Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
var sqlconnection = @"Server=DESKTOP-2MS3DR5\SANLAB;Database=Lab;userid=sa;password=password@123;";
services.AddDbContext<用户Context>(dbcontextoption => dbcontextoption.UseSqlServer(sqlconnection));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
怎么样 to create our database
我们将创建一个数据库并为我们的模型创建表。
- 转到Visual 工作室工具,指向NuGet程序包管理器,然后单击程序包管理器控制台菜单
- 有时之后,成功打包控制台管理器并准备就绪
- 输入Add-Migration MyFirstMigration并输入

如果您收到诸如“术语'Add-Migration'未被识别为cmdlet的名称”之类的错误,请关闭并重新打开Visual 工作室。
怎么样 to create our controller
转到Controllers文件夹,右键单击Controllers文件夹,指向添加,然后单击New Item。您可以选择一个MVC控制器类,并键入类名称作为UserController,然后单击“添加”按钮。
用户Controller.cs
using Microsoft.AspNetCore.Mvc;
using ASP.NETCoreWithEFCore.Models;
using System.Linq;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace ASP.NETCoreWithEFCore.Controllers
{
public 类 用户Controller : Controller
{
private 用户Context usercontext;
public UserController(用户Context context)
{
usercontext = context;
}
// GET: /<controller>/
public IActionResult Index()
{
return View(usercontext.Users.ToList());
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(用户 user)
{
if (ModelState.IsValid)
{
usercontext.Users.Add(user);
usercontext.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
}
}
怎么样 to create view
我们必须在Views文件夹中创建一个用户文件夹。之后,您可以按照以下步骤将视图页面添加到views文件夹下。
转到“用户”文件夹,右键单击“用户”文件夹,然后指向“添加”,然后单击“新建项目”。您可以选择“ MVC视图”页面,并输入文件名作为“索引”,然后单击“添加”按钮。
Index.cshtml
@model IEnumerable<ASP.NETCoreWithEFCore.Models.用户>
@{
ViewBag.Title = "用户 Page";
}
<h2 类="panel-heading">用户 Dashboard</h2>
<p>
<a asp-controller="用户" asp-action="创造">New User</a>
</p>
<table 类="table table-responsive">
<tr>
<th>用户 Id</th>
<th>Name</th>
<th>Location</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem=> item.UserId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Location)
</td>
</tr>
}
</table>
转到“用户”文件夹,右键单击“用户”文件夹,然后指向“添加”,然后单击“新建项目”。您可以选择“ MVC视图”页面,并将文件名键入“创建”,然后单击“添加”按钮。
创造.cshtml
@model ASP.NETCoreWithEFCore.Models.用户
@{
ViewBag.Title = "New User";
}
<h2>@ViewData["Title"]</h2>
<form asp-controller="用户" asp-action="创造" method="post" 类="form-horizontal" role="form">
<div 类="form-horizontal">
<div asp-validation-summary="All" 类="text-danger"></div>
<div 类="form-group">
<label asp-for="Name" 类="col-md-2 control-label"></label>
<div 类="col-md-10">
<input asp-for="Name" 类="form-control" />
<span asp-validation-for="Name" 类="text-danger"></span>
</div>
</div>
<div 类="form-group">
<label asp-for="Location" 类="col-md-2 control-label"></label>
<div 类="col-md-10">
<input asp-for="Location" 类="form-control" />
<span asp-validation-for="Location" 类="text-danger"></span>
</div>
</div>
<div 类="form-group">
<div 类="col-md-offset-2 col-md-10">
<input type="submit" value="创造" 类="btn btn-default" />
</div>
</div>
</div>
</form>
怎么样 to Run the User Management application
现在,您可以运行用户管理应用程序,它将在浏览器中构建并打开。



源代码
您可以将免费源代码下载到 下载
参考
结论
我希望您理解在Windows上使用EF 核心开发ASP.Net 核心 网页应用程序并在其上运行。我已经介绍了所有必需的东西。如果您发现我在本文中错过的任何内容,请告诉我。请分享您的宝贵意见或建议。