Here is my model of three entities: Route, Location and LocationInRoute.

The following method fails and gets an exception when it is committed:
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; }
While doing:
InsertRouteIfNotExists(companyId, locations); UnitOfWork.Commit();
I got:
Unable to determine the primary end of the relationship "SimTaskModel.FK_T_STF_SUB_LOCATION_IN_ROUTE_T_STF_LOCATION_location_id". Multiple objects added can have the same primary key.
When splitting a commit and an insert in a method, this works:
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; }
I would like to call commit once and outside the method. Why does the first example fail and what does this exception mean?
Naor May 18 '11 at 7:06 AM 2011-05-18 07:06
source share