Core3.0 EntityFrameWork DbFirst and CodeFirst

DbFirst

Asp.net Core3.0 MVC下使用EntityFrameWork框架实现DbFirst

一:生成

DbFirst 数据库优先

首先NuGet引入以下包

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkC ore.Tools

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore. SqlServer.Design

其次在程序包管理器控制台输入:

Scaffold-DbContext "Server=.;database=Core;uid=sa;pwd=123456" (数据库连接字符串)Microsoft.EntityFrameworkCore.SqlServer -OutputDir GeneralModels(任意文件夹名)

回车即可

生成后如下图

Ps:

CoreContext.cs是DbFirst根据数据库名称自动生成的数据库上下文类,不要擅自更改以免报错

 

然后打开上下文类注释掉OnConfiguring方法或者三个方法一起注释掉

其次打开appsettings.json文件,加入红色框中字符串,将其数据库连接写入配置文件。

最后打开Startup类,在ConfigureServices中注册添加代码:

即可

二:使用上下文增删改查

举例:在HomeController中使用上下文查询数据,在这里需要用到依赖注入中的构造函数注入,这里不过多阐述依赖注入原理,仅实现此次功能。

首先:声明一个上下文私有变量

private readonly CoreContext _coreContext;

然后:实例一个HomeConroller构造函数

public HomeController(CoreContext coreContext)

{

this._coreContext = coreContext;

}

这样我们就拿到了数据库上下文这个实例。

最后我们就可以进行增删改查了

这里直接贴出代码

 

如果数据库有修改字段或者表

在上面创建的命令后面 添加 -f 就好,-f 表示 -Force 覆盖

增、改、查的测试在下面

如果遇到 Build failed. 且没有提示,请把 项目 生成成功不报错了再执行

CodeFirst

先引用 NuGet 包

再编写继承自 DbContext 的数据库上下文类

using CodeFirstLibrary.Model;
using Microsoft.EntityFrameworkCore;

namespace CodeFirstLibrary
{
    public class GangHoodContext : DbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Account>().HasIndex(a=>a.AccountName).IsUnique();
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string sqlConnection = "Server=.;database=GangHood;uid=sa;pwd=123456";
            optionsBuilder.UseSqlServer(sqlConnection);

            // var builder = new ConfigurationBuilder()
            //.SetBasePath(Directory.GetCurrentDirectory())
            //.AddJsonFile("appsettings.json");
            // var configuration = builder.Build();
            // var conn = configuration.GetConnectionString("JDDbConnection");

            //optionsBuilder.UseSqlServer(this._IConfiguration.GetConnectionString("JDDbConnectionString"));


            //optionsBuilder.UseLoggerFactory(new CustomEFLoggerFactory());

            //optionsBuilder.UseSqlServer(StaticConstraint.JDDbConnection);

            //optionsBuilder.UseSqlServer("Server=.;Database=advanced11;User id=sa;password=Passw0rd");



        }


        #region 表
        public DbSet<User> Users { get; set; }
        public DbSet<Account> Accounts { get; set; }
        #endregion

    }
}

添加表的映射类

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CodeFirstLibrary.Model
{
    [Table("Accounts")]
    public  class Account
    {
        [Key]
        public long Id { get; set; }

        [MaxLength(50),Required]
        public string AccountName { get; set; }

        [MaxLength(100)]
        public string Password { get; set; }
    }
}

添加迁移文件(Add-Migration 版本说明)

更新数据库 (Update-Database 版本说明--对应上面迁移的版本说明)

测试  增、改、查

public IActionResult Index()
        {
            #region code first  测试
            using (GangHoodContext gangHoodContext = new GangHoodContext())
            {
                gangHoodContext.Add<User>(new User() { Name = $"小明{DateTimeOffset.Now.ToUnixTimeSeconds()}" });
                gangHoodContext.SaveChanges();

                User user =
                gangHoodContext.Users.FirstOrDefault(a => a.Id == 2);
                user.Name = $"小芬{DateTimeOffset.Now.ToUnixTimeSeconds()}";

                gangHoodContext.SaveChanges();

                List<User> users = gangHoodContext.Users.OrderByDescending(a => a.Id).Take(3).ToList();
                ViewBag.Users = users;
            }
            #endregion

            #region db first  测试
            using (StudyDataContext studyDataContext = new StudyDataContext())
            {
                studyDataContext.Add<People>(new People() { Name = $"赵云{DateTimeOffset.Now.ToUnixTimeSeconds()}",Age=DateTime.Now.Second });
                studyDataContext.SaveChanges();

                People people =
                studyDataContext.People.FirstOrDefault(a => a.Id == 8);
                people.Name = $"张飞{DateTimeOffset.Now.ToUnixTimeSeconds()}";
                studyDataContext.SaveChanges();

                List<People> peoples = studyDataContext.People.OrderByDescending(a => a.Id).Take(3).ToList();
                ViewBag.Peoples = peoples;
            }
            #endregion

            return View();
        }
@{
    ViewData["Title"] = "Home Page";
}
@using CodeFirstLibrary.Model
@using DBModelLibrary.DbModel

    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

        <p>CodeFirst</p>
        <dl>
            @foreach (User item in ViewBag.Users)
            {
                <dd>
                    @item.Name
                </dd>
            }
        </dl>
        <br />
        <p>DbFirst</p>
        <ol>
            @foreach (People item in ViewBag.Peoples)
            {
                <li>
                    @item.Name--@item.Age
                </li>
            }
        </ol>
    </div>