【发布时间】:2011-08-27 19:36:39
【问题描述】:
这是我的 3 个实体模型:Route、Location 和 LocationInRoute。
以下方法在提交时失败并得到异常:
public static Route InsertRouteIfNotExists(Guid companyId, IListLocation> locations)
{
//Loop on locations and insert it without commit
InsertLocations(companyId, routesOrLocations);
RouteRepository routeRep = new RouteRepository();
Route route = routeRep.FindRoute(companyId, locations);
if (route == null)
{
route = new Route()
{
CompanyId = companyId,
IsDeleted = false
};
routeRep.Insert(route);
LocationInRouteRepository locInRouteRep = new LocationInRouteRepository();
for (int i = 0; i < locations.Count; i++)
{
locInRouteRep.Insert(new LocationInRoute()
{
//Id = i,
LocationId = locations[i].Id,
Order = i,
RouteId = route.Id
});
}
}
return route;
}
做的时候:
InsertRouteIfNotExists(companyId, locations);
UnitOfWork.Commit();
我明白了:
无法确定“SimTaskModel.FK_T_STF_SUB_LOCATION_IN_ROUTE_T_STF_LOCATION_location_id”关系的主体端。多个添加的实体可能具有相同的主键。
当拆分提交并插入到方法中时 - 它可以工作:
public static Route InsertRouteIfNotExists(Guid companyId, IListLocation> locations)
{
//Loop on locations and insert it without commit
InsertLocations(companyId, routesOrLocations);
UnitOfWork.Commit();
RouteRepository routeRep = new RouteRepository();
Route route = routeRep.FindRoute(companyId, locations);
if (route == null)
{
route = new Route()
{
CompanyId = companyId,
IsDeleted = false
};
routeRep.Insert(route);
LocationInRouteRepository locInRouteRep = new LocationInRouteRepository();
for (int i = 0; i < locations.Count; i++)
{
locInRouteRep.Insert(new LocationInRoute()
{
//Id = i,
LocationId = locations[i].Id,
Order = i,
RouteId = route.Id
});
}
UnitOfWork.Commit();
}
return route;
}
我想在方法之外调用一次提交。为什么它在第一个示例中失败,这个异常意味着什么?
【问题讨论】:
-
@Ladislav Mrnka:我没有老板,这是我的项目。我真的不知道您从哪里得到我立即询问 SO 的印象。你不是唯一一个整天使用电脑的人。免费咨询?有人会保证他的答案吗?我相信这是一个可以在这里提问的论坛,这就是我正在做的事情。我有很多问题,我相信感谢这个论坛和像你这样的人,我做了很长的学习。参与是一种选择。
-
@Ladislav:我只看到一个问得相当好的问题,而且 OP 的个人资料也没有表明任何内容。
-
您是在整个操作范围内使用相同的 ObjectContext,还是每个新的存储库都有自己的 ObjectContext?
-
@Akash Kava:我使用的是同一个 ObjectContext。
标签: c# .net entity-framework