.net core使用EFCore

添加类库NetCoreDemo.EF

添加引用Microsoft.EntityFrameworkCore,    Microsoft.EntityFrameworkCore.SqlServer.Design,

Microsoft.EntityFrameworkCore.SqlServer,   Microsoft.EntityFrameworkCore.Tools四个包

 

法一:

工具-》Nuget包管理器 -》程序包管理器控制台(控制台的默认项目必须是NetCoreDemo.EF)

使用语句

Scaffold-DbContext -Connection "Server=127.0.0.1;Database=NetCoreDemo;Integrated Security=False;User ID=sa;Password=123456" -Provider "Microsoft.EntityFrameworkCore.SqlServer" -OutputDir Models

即可生成数据库表对应的类,类包含在Models文件夹 内

 

法二:

将上面四个类 中的Microsoft.EntityFrameworkCore.SqlServer.Design换成Microsoft.EntityFrameworkCore.Design

手动添加上下文类:

 

public class MyDbContext:DbContext
    {
        public MyDbContext(DbContextOptions<MyDbContext> options)
           : base(options)
        {
        }

        public DbSet<Blog> Blog { get; set; }
        public DbSet<Post> Post { get; set; }
    }

添加实体类

[Table("Blog")]
    public class Blog
    {
        [Key]
        public int BlogId { get; set; }
        public string Url { get; set; }
        public virtual List<Post> Posts { get; set; }
    }

    [Table("Post")]
    public class Post
    {
        [Key]
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }

 

主项目(web项目)的startup.cs的ConfigureServices中添加

            #region 使用EF
            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<MyDbContext>(options =>
            options.UseSqlServer(connectionString));
            #endregion

然后在它的appsetting.json里面添加连接字符串(自己定义)

"ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=Blog;Integrated Security=True"
  },

还要在主项目中加入Microsoft.EntityFrameworkCore.Design

 

以上是在主项目中定义连接字符串。EF类库只是起到声明DbContext子类的作用。

 

如果想要在EF类库里面定义连接字符串的话,那么声明方式如下:

    public class MyDbContext : DbContext
    {
        private readonly string connStr = "Data Source=.;Initial Catalog=Blog;Integrated Security=True"; 

protected override void OnConfiguring(DbContextOptionsBuilder optionBuilder) { optionBuilder.UseSqlServer(connStr); }

public DbSet<UserInfo> UserInfo { get; set; }
}

 

【CodeFirst数据迁移】

按法一打开控制台(此时启动项目必须是声明MyDbContext的项目)

输入

Add-Migration FirstMigration

就可以看到EF项目中多了一个Migrations文件夹

再输入

update-database FirstMigration

这里的FirstMigaration可以自定义名称,但两次的名称要求一样

就可以实现数据库同步

 

最后注意的是那四个包的版本号最好一致,否则可能会报错

posted @ 2021-06-09 10:32  RookieCoderAdu  阅读(307)  评论(0编辑  收藏  举报