jcl*_*son 5 c# sql entity-framework ef-code-first
我想知道是否有人可以建议我如何在 EF6 中首先使用代码完成以下任务

如果我将 Table_3 作为列表添加到我的实体中的 Table_1 和 Table_2 中。EF 自动为 Table_3 中的两个表生成外键列,而不是识别它们具有相同的类型。
我的模型类设置如下。
public interface IParent
{
int ID { get; set; }
List<Table_3> Children { get; set; }
}
public class Table_1 : IParent
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public virtual List<Table_3> Children { get; set; }
}
public class Table_2 : IParent
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public virtual List<Table_3> Children { get; set; }
}
public class Table_3
{
[Key]
public int ID { get; set; }
public int ParentID { get; set; }
[ForeignKey("ParentID")]
public virtual IParent Parent { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
EF代码首先生成以下内容

只是为了让有同样问题的人知道
我现在已经通过将 IParent 接口更改为抽象类解决了这个问题,我的类现在如下所示
[Table("ParentBase")]
public abstract class ParentBase
{
[Key]
public int ID { get; set; }
public List<Table_3> Children { get; set; }
}
[Table("Table_1")]
public class Table_1 : ParentBase
{
public string Name { get; set; }
}
[Table("Table_2")]
public class Table_2 : ParentBase
{
public string Name { get; set; }
}
[Table("Table_3")]
public class Table_3
{
[Key]
public int ID { get; set; }
public int ParentID { get; set; }
[ForeignKey("ParentID")]
public virtual ParentBase Parent { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
餐桌布置为

这会起作用,尽管如果能满足原来的要求就更好了。
我也遇到了这个问题,我从一开始就使用抽象类而不是接口。我的问题是我的 table_3 有两个导航属性:一个是公共虚拟 Table_1,另一个是公共虚拟 Table_2,然后 EF 只是配置这些额外的外键列,我将这两个导航属性合并为一个,然后它就起作用了
public virtual parentbase {get;set;}.。希望这可以帮助。
旁注,建议在 public List Children { get; 上添加 virtual 关键字 放; 在父基类中,因为在前面的示例中,它已经是这样了。
感谢您发帖,我也遇到了这个问题。