mip*_*ips 30 entity-framework entity-framework-5
我开始使用Entity Framework 4.3 Code First进行手动迁移和SQL Express 2008并最近更新到EF5(在VS 2010中),并注意到现在当我更改类似外键约束时,迁移代码会添加"dbo".到表名的开头,因此它构造的外键名称对于现有约束是不正确的(现在通常看起来很奇怪).
EF 4.3中的原始迁移脚本(注意ForeignKey("Products",t => t.Product_Id)):
CreateTable(
"Products",
c => new
{
Id = c.Int(nullable: false, identity: true),
ProductName = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"KitComponents",
c => new
{
Id = c.Int(nullable: false, identity: true),
Component_Id = c.Int(),
Product_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("Products", t => t.Component_Id)
.ForeignKey("Products", t => t.Product_Id)
.Index(t => t.Component_Id)
.Index(t => t.Product_Id);
Run Code Online (Sandbox Code Playgroud)
生成的外键名称:FK_KitComponents_Products_Product_Id FK_KitComponents_Products_Component_Id
如果我然后升级到EF5并更改外键,则迁移代码看起来像(注意"dbo.KitComponents"和"dbo.Products"而不是"KitComponents"和"Products"):
DropForeignKey("dbo.KitComponents", "Product_Id", "dbo.Products");
DropIndex("dbo.KitComponents", new[] { "Product_Id" });
Run Code Online (Sandbox Code Playgroud)
并且update-database失败并显示以下消息:' FK_dbo.KitComponents_dbo.Products_Product_Id '不是约束.无法删除约束.查看以前的错误.
因此,从EF5开始,约束命名已从FK_KitComponents_Products_Product_Id更改为FK_dbo.KitComponents_dbo.Products_Product_Id(使用dbo.前缀)
我怎样才能让EF5在EF 4.3中表现得如此,所以我不必改变它吐出的每一个新的迁移代码?
我一直无法找到任何关于为什么会改变以及如何应对的发布说明:(
bri*_*lam 32
您可以通过对CSharpMigrationCodeGenerator类进行子类化来自定义生成的代码:
class MyCodeGenerator : CSharpMigrationCodeGenerator
{
protected override void Generate(
DropIndexOperation dropIndexOperation, IndentedTextWriter writer)
{
dropIndexOperation.Table = StripDbo(dropIndexOperation.Table);
base.Generate(dropIndexOperation, writer);
}
// TODO: Override other Generate overloads that involve table names
private string StripDbo(string table)
{
if (table.StartsWith("dbo."))
{
return table.Substring(4);
}
return table;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在迁移配置类中进行设置:
class Configuration : DbMigrationsConfiguration<MyContext>
{
public Configuration()
{
CodeGenerator = new MyCodeGenerator();
}
}
Run Code Online (Sandbox Code Playgroud)
对于自动迁移,请使用以下代码:
public class MyOwnMySqlMigrationSqlGenerator : MySqlMigrationSqlGenerator
{
protected override MigrationStatement Generate(AddForeignKeyOperation addForeignKeyOperation)
{
addForeignKeyOperation.PrincipalTable = addForeignKeyOperation.PrincipalTable.Replace("dbo.", "");
addForeignKeyOperation.DependentTable = addForeignKeyOperation.DependentTable.Replace("dbo.", "");
MigrationStatement ms = base.Generate(addForeignKeyOperation);
return ms;
}
}
Run Code Online (Sandbox Code Playgroud)
并在配置上进行设置:
SetSqlGenerator("MySql.Data.MySqlClient", new MyOwnMySqlMigrationSqlGenerator());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9467 次 |
| 最近记录: |