EFCore CodeFirst 入门示例

1 添加引用

添加Microsoft.EntityFrameworkCore 和 Microsoft.EntityFrameworkCore.SqlServer

2 定义数据库会话上下文

    public class TestDbContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(ConfigHelper.GetConfigConnString("TestConn"));
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
        public int Rating { get; set; }
        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        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; }
    }

3 测试 

    class Program
    {
        static void Main(string[] args)
        {
            using(var db = new TestDbContext())
            {
                // 如果数据库不存在创建数据库
                db.Database.EnsureCreated();
            }

            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }
    }

运行结果:

 

posted @ 2021-03-01 14:35  温故纳新  阅读(124)  评论(0编辑  收藏  举报