我已将2个实体Project
,Train
与多对多关系相关联。
现在,我想将现有Train
添加到Project.Trains
。不幸的是,该系列有很多条目。当我写project.Trains.Add(...)
时,它实现了完整的集合,这需要花费很多时间。有没有办法告诉EF我想在不实现集合的情况下将Train添加到项目中,以便更快地采取行动?
答案 0 :(得分:1)
假设Train.Projects
集合的项项比<{1}}项更少,快速解决方案是将Project.Trains
添加到Project
而不是相反:
Train
答案 1 :(得分:1)
Yes, there is a way of doing it, but it is very difficult, and it involves digging into the very interna of EF. If you use the proxies generated by EF, they will typically implement IEntityWithRelationships
. You will be able to access the relationship manager as
var entityWithRelationships = project as IEntityWithRelationships;
var relatedEnd = entityWithRelationships.RelationshipManager.GetRelatedEnd("RelationshipName as found in Metadata");
With this setup you should be able to add the Train
as follows:
context.Trains.Add(train);
relatedEnd.Add(train);
As said, it is a long way to make it work, but it would solve your problem.
答案 2 :(得分:0)
你可以:
1-关闭延迟加载。这样,访问Trains
就无法访问Train
查询到DB。但要注意副作用,因为你可能有
已经依赖它了。
2-关闭关系数据库世界:将FK属性添加到 newTrain.ProjectId = project.Id
实体并在新创建的实体上设置它
对象:
public class ProjectTrain
{
public int Id {get;set;}
public Project Project {get;set;}
public Train Train {get;set;}
}
3-更接近关系数据库世界:添加ProjectTrain的junction table,以实现多对多关系
DBSet<ProjectTrain> ProjectTrains {get;set;}
并将其添加到上下文中:
ProjectTrains
最后,创建Train
的新实体并设置Project
和position: fixed
属性