[英]Entity Framework 6: Two unrelated entities mapped to same table
我想将一个表映射到两个不相关的实体:EntityBasic和EntityAdvanced。 EntityAdvanced具有此功能不需要的其他业务逻辑,我想创建一个仅包含表中字段的新Entity。
MyTable的:
MyTableId : Guid
ParentId : Guid
Name : string
Description : string
Type : int
EntityBasic:
[Table("MyTable")]
public class EntityBasic
{
[Key]
public Guid MyTableId { get; set; }
public Guid ParentId { get; set }
public string Name { get; set; }
public string Description { get; set; }
public int Type { get; set; }
[ForeignKey("ParentId")]
public virtual List<EntityBasic> Entities{ get; set; }
}
EntityAdvanced:
[Table("MyTable")]
public class EntityAdvanced
{
private List<EntityAdvanced> _entities;
private List<Filter> _filters;
[Key]
public Guid MyTableId { get; set; }
public Guid ParentId { get; set }
public string Name { get; set; }
public string Description { get; set; }
public int Type { get; set; }
[ForeignKey("ParentId")]
public virtual List<EntityAdvanced> Entities
{
get { //Some complicated getter }
set { //Some complicated setter }
}
[NotMapped]
public string ImageUrl
{
get { //Some complicated getter }
set { //Some complicated setter }
}
public void SetFilters(//Some parameters)
{
//Some logic
}
}
当我这样做时,我得到这个错误:
实体类型“ EntityAdvanced”和“ EntityBasic”不能共享表“ MyTable”,因为它们不在同一类型层次结构中,或者没有有效的一对一外键关系且它们之间具有匹配的主键。
有什么方法可以做我想要的吗?
首先,您的EntityAdvanced
应该继承EntityBasic,因为它们共享相同的基本属性集。 您无需重写它们。 请注意extends EntityBasic
。
[Table("MyTable")]
public class EntityBasic
{
[Key]
public Guid MyTableId { get; set; }
public Guid ParentId { get; set }
public string Name { get; set; }
public string Description { get; set; }
public int Type { get; set; }
[ForeignKey("ParentId")]
public virtual List<EntityBasic> Entities{ get; set; }
}
[NotMapped]
public class EntityAdvanced : EntityBasic
{
//[NotMapped]
public string ImageUrl
{
get { //Some complicated getter }
set { //Some complicated setter }
}
public void SetFilters(//Some parameters)
{
//Some logic
}
}
使用继承, List<EntityBasic> Entities
可以引用EntityAdvanced
对象,因此您不再需要声明:
[ForeignKey("ParentId")]
public virtual List<EntityAdvanced> Entities
{
get { //Some complicated getter }
set { //Some complicated setter }
}
您可以在此处获得有关使用Entity Framework实现继承的有用信息。
编码愉快!
我认为您可以使用Entity Framework 6的“表拆分”功能,在此处查看示例: https : //www.c-sharpcorner.com/UploadFile/ff2f08/table-splitting-in-entity-framework- 6-代码优先的方法/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.