.Net Core Mvc中使用EF

发布于 2017-06-27  216 次阅读


折腾完AutoMapper了再折腾下EF
1.添加下需要的包 下列是需要使用的

"dependencies": {
"Microsoft.EntityFrameworkCore": "1.1.2",
"Microsoft.EntityFrameworkCore.Design": "1.1.2",
"Microsoft.Extensions.Logging.Abstractions": "1.1.2",
"Microsoft.EntityFrameworkCore.SqlServer": "1.1.2"
},
"tools": {
    "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4-final",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.1.0-preview4-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  }

2.新建一个实体类

  public class UserEntity
{
   public string LoginName { get; set; }
   public string RealName { get; set; }
}

3.新建一个数据库上下文对象context

  public class lkWebContext : DbContext
    {
        public DbSet Users { get; set; }
      public lkWebContext(DbContextOptions options) : base(options)
        {
        }
    }

4.在Startup.cs中的ConfigureServices方法中增加一条语句 为了添加EF 其中的lkWeb为项目名 似乎就是主项目的那个dll名 MigrationsAssembly是为了之后用migrations命令准备的

  
            services.AddEntityFrameworkSqlServer().AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("lkWebConn"), b => b.MigrationsAssembly("lkWeb")));

5.在appsettings.json中添加下数据库连接串

 "ConnectionStrings": {
    "lkWebConn": "Password=XXX;Persist Security Info=True;User ID=sa;Initial Catalog=lkWeb;Data Source=."
  }

6.初始化下数据库
在cmd控制台输入命令来实现code first
首先打开cmd 切换到项目的project.json 文件所在文件。执行如下命令 要用这个命令要先安装Microsoft.EntityFrameworkCore.Tools 和Microsoft.EntityFrameworkCore.Tools.DotNet

dotnet ef migrations add FirstMigration 
dotnet ef database update

另一种方法

在vs的PM命令输入 Add-Migration lkWeb
成功后会在项目中产生一个Migrations文件夹。里面有个快照文件和一个迁移的文件。lkWebContextModelSnapshot.cs 和20170626143300_lkMigration.cs
再执行命令: Update-Database lkWeb

注:使用migration要新建一个类,不然执行命令时会提示错误
 public class lkWebDbContextFactory : IDesignTimeDbContextFactory<lkWebContext>
 {
 public lkWebContext CreateDbContext(string[] args)
 {
 string connectionString = "Password=XXX;Persist Security Info=True;User ID=sa;Initial Catalog=lkWeb;Data Source=.";

 var builder = new DbContextOptionsBuilder<lkWebContext>();

 builder.UseSqlServer(connectionString);
 return new lkWebContext(builder.Options);
 }
 }

7.使用

 public class HomeController : Controller
    {
        private lkWebContext _context;
        public HomeController(lkWebContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            UserEntity user = new UserEntity { LoginName = "admin", RealName = "管理员" };
            _context.Users.Add(user);
            _context.SaveChanges();
            return View();
        }
}

LoneKing