2016-03-28 154 views
0

我嘗試解決以下:EF代碼優先映射一個表到一些實體

在實體HRCardBPCard我有屬性

public int DefaultAddressId { get; set; } 

[ForeignKey("DefaultAddressId")] 
public AddressDetail Address { get; set; } // table AddressDetail 

至今沒有問題,現在我的問題: 在BPCard我有另外一個屬性:

public virtual ICollection<AddressDetail> Addresses { get; set; } //table AddressDetail 

完整的代碼如下:

public abstract class EntityBase : IEntityModel { 
[Key] 
public int EntityId { get; set; } 

[Required] 
[StringLength(50)] 
public string EntityKey { get; set; } 

//... 
} 

// table HRCards 
public class HRCard : EntityBase { 
//Id from base class 
// working fine 
//... 

public int DefaultAddressId { get; set; } 

[ForeignKey("DefaultAddressId")] 
public AddressDetail Address { get; set; } // table AddressDetail 
} 

// table BPCards 
public class BPCard : EntityBase { 
//Id from base class 
// working fine 
//... 
public int DefaultAddressId { get; set; } 
public int DefaultContactId { get; set; } 

//working fine 
[ForeignKey("DefaultAddressId")] 
public AddressDetail DefaultAddress { get; set; } //table AddressDetail 

//how can i solve this?? 
// table AddressDetail 
public virtual ICollection<AddressDetail> Addresses { get; set; } 
} 

public class AddressDetail : EntityBase { 
//Id from base class 
// working fine 
//... 
public int ParentId { get; set; } 
} 

我有很長一段時間尋找,但沒有結果真正解決我的問題。我的第一個解決方案是將表分成HRAddress和BPAddress,這工作正常。

編輯: 如果我開始啓用遷移我得到一個錯誤信息:

「屬性‘的ParentId’不能被配置爲導航屬性的屬性必須是有效的實體類型和屬性應該有一個非抽象的getter和setter。對於集合屬性,類型必須實現ICollection,其中T是有效的實體類型。「

千恩萬謝

PS: 我可以改變標籤後更好的映射?

+0

目前尚不清楚問題是什麼或你想達到什麼目的。 – Szer

+0

我先使用代碼,並且遷移工具運行時出錯。 //我該如何解決這個問題? public virtual ICollection Addresses {get;組; } – FaceOfIngo

+0

@FaceOfIngo哪個錯誤?編輯它在你的問題請 –

回答

0

這取決於與地址你想要的預期關係POCO

可以使用的東西的註解像

public class AddressDetail : EntityBase { 
//Id from base class 

public virtual ICollection<BPCard> Addresses { get; set; } 
//public virtual BPCard Addresses { get; set; } 
public virtual ICollection<HRCard> Addresses { get; set; } 
//public virtual BPCard Addresses { get; set; } 
} 
上的東西你的模型像

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
     //one-to-many 
     modelBuilder.Entity<HRCard>() 
        .HasMany<AddressDetails>(s => s.Id) 
        .WithRequired(s => s.HRCard) 
        .HasForeignKey(s => s.AddressId); 
} 

,或者直接解決關係

相關問題