我在配置EF映射時遇到了一些問題。實體框架 - 配置識別密鑰
我具有以下類(每個字典可具有0,1或許多對象):
public class Dictionary
{
public virtual ICollection<DictionaryDomain> Domains { get; set; }
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class DictionaryDomain
{
public virtual Dictionary Dictionary { get; set; }
public virtual int DictionaryId { get; set; } // I have added this after error described below
public virtual Domain Domain { get; set; }
public virtual int Id { get; set; }
}
public class Domain
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
當我刪除域(僞碼)
Dictionary d = GetDictionary();
d.Domains.remove(some_object);
我得到一個錯誤:
A relationship from the 'DictionaryDomain_Dictionary' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'DictionaryDomain_Dictionary_Source' must also in the 'Deleted' state.
因此,我已將DictionaryId
添加到類作爲重點,並配置類的部分是這樣的:
modelBuilder.Entity<Dictionary>()
.HasKey(e => e.Id);
modelBuilder.Entity<Dictionary>()
.Property(e => e.Name).IsRequired().HasMaxLength(200);
modelBuilder.Entity<DictionaryDomain>()
.HasRequired(e => e.Dictionary);
// Added from this line
modelBuilder.Entity<DictionaryDomain>()
.HasKey(e => new { e.Id, e.DictionaryId });
modelBuilder.Entity<DictionaryDomain>()
.Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<DictionaryDomain>()
.Property(e => e.DictionaryId).HasColumnName("Dictionary_Id");
// Till this line
modelBuilder.Entity<DictionaryDomain>()
.HasRequired(e => e.Domain);
modelBuilder.Entity<Domain>()
.HasKey(e => e.Id);
modelBuilder.Entity<Domain>()
.Property(e => e.Name).IsRequired().HasMaxLength(200);
但之後我加入我得到了一些奇怪的移民遷移:
public override void Up()
{
DropIndex("dbo.DictionaryDomains", new[] { "Domain_Id" });
DropColumn("dbo.DictionaryDomains", "Id");
RenameColumn(table: "dbo.DictionaryDomains", name: "Domain_Id", newName: "Id");
DropPrimaryKey("dbo.DictionaryDomains");
AlterColumn("dbo.DictionaryDomains", "Id", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.DictionaryDomains", new[] { "Id", "Dictionary_Id" });
CreateIndex("dbo.DictionaryDomains", "Id");
}
這不是我所期待的(我的預期只有主鍵的娛樂)。
我不知道我做錯了什麼。也許我沒有足夠的瞭解EF如何工作,但任何提示將不勝感激。
感謝