我尝试解决以下问题:
在实体 HRCard 和 BPCard 中我有属性
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是a有效的实体类型。“
非常感谢PS: 我可以稍后更改标签以获得更好的映射吗?
答案 0 :(得分: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);
}