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

 

转载于:https://www.cnblogs.com/TiestoRay/p/5761521.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值