zoukankan      html  css  js  c++  java
  • EF深入系列--Code First

    首先是创建DbContext,有两种途径

    ①手动编写DbContext代码,同时还要记得去配置文件中添加connectionStrings

    public class BooksContext : DbContext
    {
        public BooksContext() : base("name=BooksContext")
        {
    
        }
    
        public DbSet<Book> Books { get; set; }
    }

    ②通过创建Controller指定自动生成DbContext

     在创建完一个Model之后,右击Controller文件夹(MVC项目的话),新建Controller,弹出这样的弹窗

     

    这样添加了Controller也会自动创建一个Context类,同时webconfig也会自动添加connectionString

    然后在包管理器控制台输入enable-migrations,会自动创建/Migrations/Configuration.cs文件

    为了启用Code First,需要将Configuration类的构造函数中AutomaticMigrationsEnabled设为true

    初次建库可以NPM执行 add-migration Initial 

    若数据库有更改 可以执行 update-database ,会执行Configuration.Seed函数(函数内放入数据迁移的代码)

     生成的Configuration.cs文件

    internal sealed class Configuration : DbMigrationsConfiguration<Models.BooksContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }
    
        protected override void Seed(Models.BooksContext context)
        {
            context.Authors.AddOrUpdate(new Author[] {
                new Author() { AuthorId = 1, Name = "Ralls, Kim" },
                new Author() { AuthorId = 2, Name = "Corets, Eva" }
            });
    
            context.Books.AddOrUpdate(new Book[] {
                new Book() { BookId = 1,  Title= "Midnight Rain", Genre = "Fantasy",
                PublishDate = new DateTime(2000, 12, 16), AuthorId = 1, Description =
                "A former architect battles an evil sorceress.", Price = 14.95M
                }
            });
        }
    }

    关于Code First的相关文章:msdn

  • 相关阅读:
    漫画 | 一台Linux服务器最多能支撑多少个TCP连接?
    frida hook pthread_create
    mac搜索so中的字符串
    字节字符串和数字互转
    twsited使用延迟项,并发量限制
    常见汇编指令和EFLAGS寄存器对应位的含义
    scrapy设置cookie的三种方式
    G1GC 读书笔记
    SLF4J 适配图
    支付宝和微信提现有办法免费了!
  • 原文地址:https://www.cnblogs.com/TiestoRay/p/5761521.html
Copyright © 2011-2022 走看看