下面我们来演示一下使用EF Core Sqlserver数据库。
引入EF
使用NUGET来安装
引用 EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore
引用 EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.SqlServer
引用 EntityFrameworkCore.SqlServer.Tools
Install-Package Microsoft.EntityFrameworkCore.Tools
在appsettings.json 文件中添加sqlserver的数据库链接配置
{
"ConnectionStrings": {
"SqlServerConnection": "Server=.;Database=firstcoremvc;User ID=sa;Password=qweqwe;"
},
"Logging": {Code language: JSON / JSON with Comments (json)
注册EF服务
public void ConfigureServices(IServiceCollection services)
{
var sqlConnection = Configuration.GetConnectionString("SqlServerConnection");
services.AddDbContext<MyDBContent>(option => option.UseSqlServer(sqlConnection));Code language: JavaScript (javascript)
添加实体对象 不过我们这里使用UserInfo
public class UserInfo
{
private int id;
private string name;
private string password;
private string comfirmpassword;
//增加这个标注 则这个属性就不会被绑定
[BindNever]
public int Id { get => id; set => id = value; }
//增加这个标注 则这个属性 必须绑定 如果没有绑定 则会抛出错误的
[BindRequired]
[Display(Name="用户名")]
[StringLength(maximumLength:15,MinimumLength =6)]
[Remote("VerifyName","User")]//指明使用哪个action来进行验证
public string Name { get => name; set => name = value; }
[Required]
[Display(Name = "密码")]
public string Password { get => password; set => password = value; }
[Display(Name = "确认密码")]
[Compare("Password",ErrorMessage = "{0}和{1}必须一样")]
public string Comfirmpassword { get => comfirmpassword; set => comfirmpassword = value; }
}Code language: PHP (php)
配置EF上下文
public class MyDBContent: DbContext
{
public MyDBContent(DbContextOptions<MyDBContent> options) : base(options)
{
}
public DbSet<UserInfo> Users { get; set; }
}Code language: HTML, XML (xml)
打开程序包管理控制台,执行 Add-Migration Migrations 命令,
注意此时默认启动项目必须是Model所在项目
如果顺利的话项目下应该会生成一个Migrations的文件夹并包含一些初始化生成数据库需要用的文件
执行 update-database 命令生成数据库
Previous: 39-在控制器中使用配置
Next: 41-EF Core数据升级