Entity Framework Code First 中的基类和父/子关系
您好,我遇到了抽象基类及其实现
public class SuperParent
{
public ICollection<Parent> ParentList { get; set; }
}
public abstract class Parent
{
public int Id { get; set; }
public string Title { get; set; }
}
public abstract class ParentExtended : Parent
{
public ICollection<ChildClass> ChildClassList { get; set; }
}
public class RealClass : ParentExtended
{
}
public class ChildClass
{
public int Id { get; set; }
public Parent Parent { get; set; }
}
DBContext 之间的父/子关系问题,如下所示:
public DbSet<SuperParent> SuperParents { get; set; }
public DbSet<Parent> Parents { get; set; }
public DbSet<ChildClass> ChildClasses { get; set; }
示例代码
SuperParent sp = new SuperParent();
sp.ParentList = new List<Parent>();
RealClass parent = new RealClass();
parent.ChildClassList = new List<ChildClass>();
parent.ChildClassList.Add(new ChildClass());
sp.ParentList.Add(parent);
数据库表 ChildClass 中的结果,其中列
- Id
- Parentid(FK)
- ParentExtendedId(FK) ,
其中 ParentId 始终为 null,parentExtendedId填充了正确的 ID,但不需要。
我的问题是这是要走的路,我怎样才能将子类 Parent 作为父级而不是 ParentExtended
Hi I've run into a problem with Parent/Child Relations between abstract baseclasses and their implementations
public class SuperParent
{
public ICollection<Parent> ParentList { get; set; }
}
public abstract class Parent
{
public int Id { get; set; }
public string Title { get; set; }
}
public abstract class ParentExtended : Parent
{
public ICollection<ChildClass> ChildClassList { get; set; }
}
public class RealClass : ParentExtended
{
}
public class ChildClass
{
public int Id { get; set; }
public Parent Parent { get; set; }
}
DBContext looks as follows:
public DbSet<SuperParent> SuperParents { get; set; }
public DbSet<Parent> Parents { get; set; }
public DbSet<ChildClass> ChildClasses { get; set; }
Example code
SuperParent sp = new SuperParent();
sp.ParentList = new List<Parent>();
RealClass parent = new RealClass();
parent.ChildClassList = new List<ChildClass>();
parent.ChildClassList.Add(new ChildClass());
sp.ParentList.Add(parent);
Results in the database table ChildClass with columns
- Id
- Parentid(FK)
- ParentExtendedId(FK)
where ParentId is always null, parentExtendedId is filled with the correct Id but unwanted.
My question is this the way to go and how can i give childclass Parent as a parent and not ParentExtended
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己找到了答案,而且很简单:)
使用数据注释来装饰抽象类 ParentExtended 中的子列表,该数据注释告诉该类子级中的逆属性是什么。
所以在我的示例中:
With 创建一个返回 Realclass 的指针,但在名为 Parent 的变量中
I found the answer myself and it's rather easy:)
Decorate the childlist in the abstract class ParentExtended with a data annotation that tells the class what the inverse property within the child is.
So in my example:
With creates a pointer to back to Realclass but in the variable named Parent