.NET Core学习笔记(9)——Entity Framework Core之Code First

上篇咱们介绍了怎么经过已有的SQLServer表来建立实体类,本篇咱们改用Code First的方式,由C#代码书写的实体类来生成SQLServer表。而且经过简单的Console APP往SQLServer表写入数据。
首先咱们先建立3个空的Projects,其中EfCodeFirst是做为启动项的Console程序(.NET Core 3.1)。EfCodeFirst经过Add Project Reference引用DataAccess工程(.NET Standard 2.0)。DataAccess将会包含DbContext对象,做为数据库的实际访问接口。同时DataAccess还会Add Project Reference引用Entities工程(.NET Standard 2.0)。Entities工程顾名思义,全部SQLServer表的映射实体类会写到这里。git

接着咱们经过NuGet给各个Project添加EntityFrameworkCore的引用,其中DataAccess须要EntityFrameworkCore.Tools以及EntityFrameworkCore.SqlServer,启动项EfCodeFirst须要EntityFramework.Design。github

同时还要把CodeFirst所需的代码给补上,在Entities工程中咱们添加TodoItem类:shell

namespace Entities
{
    public class TodoItem
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }
}

在DataAccess工程中咱们添加TodoContext对象,TodoContext继承自DbContext,同时还引用TodoItem类。实际咱们也正是经过TodoContext类来实现TodoItem对象在SQLServer中的增删查改。注意这里咱们经过OnConfiguring方法来指定SQLServer的Connection String。数据库

namespace DataAccess
{
    public class TodoContext : DbContext
    {
        public DbSet<TodoItem> TodoItems { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder options)
            => options.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=CodeFirstDB;Integrated Security=True;");
    }
}

 

接下来咱们就要经过在Package Manager Console窗口经过Add-Migration命令来建立SQLServer表了。注意Default project要选择DataAccess,不然Migrations相关文件会生成到别的工程。ide

InitDatabase是我给Migrations脚本指定的名字,在DataAccess工程中,会加上时间前缀生成对应的Migrations类,以以下形式呈现:函数

此时仍没有建立SQLServer表,咱们须要在Package Manager Console提示"Build succeeded."后。经过Update-Database命令来把修改应用到SQLServer中。ui

至此咱们就能够使用TodoContext来访问SQLServer中的TodoItems表了,在EfCodeFirst工程的Main函数里添加以下代码,每次Main函数启动时查询TodoItems表的记录条数,而后新增一条记录。spa

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            using (var dbContext = new TodoContext())
            {
                var count = dbContext.TodoItems.Count();
                var item = new TodoItem { Name = $"test{++count}" };
                dbContext.Add(item);
                dbContext.SaveChanges();
            }
        }

GitHub:3d

https://github.com/manupstairs/EntityFrameworkCoreSamples/tree/main/CodeFirstSamplecode

相关文章
相关标签/搜索