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

  • 相关阅读:
    使用 Spring data redis 结合 Spring cache 缓存数据配置
    Spring Web Flow 笔记
    Linux 定时实行一次任务命令
    css js 优化工具
    arch Failed to load module "intel"
    go 冒泡排序
    go (break goto continue)
    VirtualBox,Kernel driver not installed (rc=-1908)
    go运算符
    go iota
  • 原文地址:https://www.cnblogs.com/TiestoRay/p/5761521.html
Copyright © 2011-2022 走看看