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

 

posted @ 2016-08-11 16:30  TiestoRay  阅读(366)  评论(0编辑  收藏  举报