Ido*_*Ran 5 entity-framework entity-framework-4
我正在使用Entity Framework 4.4和.NET Framework 4.0构建ASP MVC网站
我已经为我的模型添加了多对多关系,如下所示:
public class User {
public int UserID { get; set; }
public string Username { get; set; }
public virtual ICollection<Tenant> Tenants { get; set; }
}
public class Tenant {
public string TenantID { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当我运行Add-Migration命令时,我得到了这个迁移类(我删除了Down方法)
public partial class TenantUsersManyToManyMigration : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.UserTenants",
c => new
{
User_UserID = c.Int(nullable: false),
Tenant_TenantID = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.User_UserID, t.Tenant_TenantID })
.ForeignKey("dbo.Users", t => t.User_UserID, cascadeDelete: true)
.ForeignKey("dbo.Tenants", t => t.Tenant_TenantID, cascadeDelete: true)
.Index(t => t.User_UserID)
.Index(t => t.Tenant_TenantID);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么TenantID和UserID的字段名称分别是User_UserID和Tenant_TenantID,而不是UserID和TenantID.
如何更改默认迁移脚手架(或我的模型)以使cascadeDelete为false?(目前我只需手动更换).
您可以使用流利的表示法以您想要的方式创建映射表.在您的DbContext类中,使用以下方法覆盖OnModelCreating:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(u => u.Tenants)
.WithMany(t => t.Users)
.Map(m =>
{
m.ToTable("UserTenants");
m.MapLeftKey("UserId");
m.MapRightKey("TenantId");
});
}
Run Code Online (Sandbox Code Playgroud)
此外,使用fluent,如果要禁用单个表上的级联删除,则可以在映射属性时使用.WillCascadeDelete(false).这是关于如何使用流利符号的MSDN上的一篇很棒的文章.
您可以通过以下方式删除级联删除约定:
using System.Data.Entity.ModelConfiguration.Conventions;
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
Run Code Online (Sandbox Code Playgroud)
然后看看脚手架是否发生变化。我个人从未使用过它。
此外,微软(某种程度上)在标题下的链接Foreign Keys中解释了 FK 命名约定。