对于新的EF项目,EntityTypeConfiguration和DbMigration之间有什么区别? [英] What is the difference between EntityTypeConfiguration and DbMigration for a new EF project

查看:259
本文介绍了对于新的EF项目,EntityTypeConfiguration和DbMigration之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该使用 EntityTypeConfiguration 构建我的数据模型,或者我应该直接启用迁移使用 DbMigration



这是使用:

  public class BlogEFCFConfiguration:EntityTypeConfiguration< Blog> {
public BlogEFCFConfiguration()
:base(){
HasKey(x => x.BlogId);
属性(x => x.BlogId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
属性(x => x.Name).HasColumnType(varchar)。HasMaxLength(128);
}
}

  public partial class InitialCreate:DbMigration {
public override void Up(){
CreateTable(
dbo.Blogs,
c => new
{
BlogId = c.Int(nullable:false,identity:true),
Name = c.String(maxLength:128,unicode:false),
})
.PrimaryKey(t => t.BlogId);

}

public override void Down(){
DropTable(dbo.Blogs);
}
}

的确,如果我想改变我的模型,我会有最后使用 DbMigration 。那么为什么要使用 EntityTypeConfiguration



这可能是一个太开放的问题。

解决方案

他们正在做不同的工作 - EF迁移确保应用程序和数据库更改是一致的。配置通知EF如何从对象模型映射到关系模型。



如果默认约定不适合您的型号,则需要配置。



如果您需要EF迁移希望在应用程序版本之间的代码中对数据库进行更改。这具有能够自动使应用程序在启动时将数据库更新到最新版本的优点。


Should I use EntityTypeConfiguration to build my data model, or should I directly enable migrations an use DbMigration.

That is use :

public class BlogEFCFConfiguration : EntityTypeConfiguration<Blog> {
    public BlogEFCFConfiguration()
        : base() {
        HasKey(x => x.BlogId);
        Property(x => x.BlogId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(x => x.Name).HasColumnType("varchar").HasMaxLength(128);
    }
}

or

public partial class InitialCreate : DbMigration {
    public override void Up() {
        CreateTable(
            "dbo.Blogs",
            c => new
                {
                    BlogId = c.Int(nullable: false, identity: true),
                    Name = c.String(maxLength: 128, unicode: false),
                })
            .PrimaryKey(t => t.BlogId);

    }

    public override void Down() {
        DropTable("dbo.Blogs");
    }
}

Indeed if I want to change my model I will have to finally use DbMigration. So why use EntityTypeConfiguration ?

It is may be a too open question.

解决方案

They are doing different jobs - EF migrations ensure that the application and database changes are aligned. The configurations inform EF how to map from your object model to your relational model.

Configurations are required when the default conventions don't suit your model.

EF migrations are required if you wish to model the database changes in code between application versions. This has the advantage of being able to automatically have the application update the database to the latest version on startup for example.

这篇关于对于新的EF项目,EntityTypeConfiguration和DbMigration之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆