实体框架中的父子链接 [英] Parent and Child Link in Entity Framework
问题描述
我正在创建类似于任务列表的系统Web应用程序。
I'm creating a system web application similar to a Task list.
- 用户可以创建任务
- 用户可以在任何任务中创建任务。
- 用户然后可以在该任务中创建任务
- 用户可以查看第一个任务,并查看与该任务链接的所有任务。
- A user can create a Task
- A User can create a Task within any Task.
- A User then can create a Task within that Task
- A User can view the First task and see all the tasks that are linked to that.
我创建了一个简单的父子关系。一旦我超过了第一级,我发现不可能吗?
I have created a simple parent and child relationship. Once I get past the first level i find it impossible?
我希望能够查看原始的父任务以及其中的所有其他父任务和子任务。
I want to be able to view the original parent task and all the other parent and child tasks within that.
到目前为止,一个Task具有一个Icollection的Task。
So far a Task has an Icollection of tasks.
我想做的是查看原始父类的所有兄弟姐妹。
What I want to be able to do is view all the siblings of the original parent class.
modelBuilder.Entity<Task>()
.HasMany(x => x.Children)
.WithOptional()
.HasForeignKey(x => x.ParentID);
推荐答案
查询数据库时,请执行以下操作:
When querying the database do the following:
var tasks = from t in db.Tasks.Include("Parent")
where t.Id //... your logic here
select t;
,您将需要扩展Task类以包括父属性:
and you will need to extend your Task class to include the parent property:
public virtual Task Parent { get; set; }
然后映射关系:
modelBuilder.Entity<Task>()
.HasOptional(x => x.Parent)
.WithMany(x => x.Children)
.HasForeignKey(x => x.ParentID);
上面的查询告诉EF为每个返回的Task带来父Task。
The query above tells EF to bring the parent Task for every returned Task.
希望这会有所帮助。
这篇关于实体框架中的父子链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!