추가 된 여러 항목이 동일한 기본 키를 가질 수 있습니다.
다음은 Route, Location 및 LocationInRoute의 3 개 엔터티 모델입니다.
다음 메서드가 실패하고 커밋 할 때 예외가 발생합니다.
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;
}
한 번 메서드 외부에서 커밋을 호출하고 싶습니다. 첫 번째 예에서 실패하는 이유와이 예외는 무엇을 의미합니까?
이 오류는 해결할 수없는 외래 키 ID (참조와 반대)로 인해 발생합니다. 귀하의 경우에는 ID가 0 인 위치를 참조하는 LocationInRole이 있습니다.이 ID를 가진 위치가 여러 개 있습니다.
The Locations have not yet been assigned an ID because they have not yet been saved to the database which is when the ID is generated. In your second example, the Locations are saved before their IDs are accessed which is why this works.
You will not be able to rely on the Location IDs to define the relationships if you want to SaveChanges only later.
Swap the following line...
LocationId = locations[i].Id
...for this...
Location = locations[i]
The relationships will then be based on object references which are not dependent on the LocationIDs.
In case this is of any use to future readers, in my case this error was due to an incorrectly configured foreign key in my database (and model generated from DB).
I had tables:
Parent (1-1) Child (1-many) Grandchild
and the Grandchild table had inadvertently received a foreign key up to it's parent (Child) and it's grandparent (Parent). On saving multiple Parent entities from new, I received this error. Fix has been to correct the foreign key.
Having run into the same error I highly suspect the actual issue was the definition of Location. Put simply, in EF Code First I bet it looked like this:
public class Location
{
public int Id { get; set; }
...
public Location ParentLocation { get; set; }
[ForeignKey("ParentLocation")]
public int ParentLocationId { get; set; }
}
In other words, in the Question, ParentLocation/ParentLocationId are a recursive reference back to this table.
The ParentLocationId is not Nullable. That means it's going to be inserted with a 0, and EF will complain on Insert, rather than when you Migrate - even though the truth is once that Migration runs you have a table EF will never let you insert into.
동일한 테이블에 대한 재귀 참조를 다시 작동하게 만드는 유일한 방법은 재귀 참조를 nullable로 만드는 것입니다.
public class Location
{
public int Id { get; set; }
...
public Location ParentLocation { get; set; }
[ForeignKey("ParentLocation")]
public int? ParentLocationId { get; set; }
}
메모 ?
애프터을 int
.
이 예외를 검색하는 경우 :
제 경우에는 필수 탐색 속성을 설정하지 못했습니다.
public class Question
{
//...
public int QuestionGridItemID { get; set; }
public virtual QuestionGridItem GridItem { get; set; }
//...
public int? OtherQuestionID { get; set; }
public Question OtherQuestion { get; set; }
}
//...
question.OtherQuestion = otherQuestion;
questionGridItem.Questions.Add(question);
dataContext.SaveChanges(); //fails because otherQuestion wasn't added to
//any grid item's Question collection
나는 같은 문제가 있었다. 아래 시나리오가 해결되었습니다. 다음과 같이 코드를 변경해야한다고 생각합니다.
var insertedRoute =routeRep.Insert(route);
.....
insertedRoute.LocationInRoute = new List<LocationInRoute>();
for(....){
var lInRoute = new LocationInRoute(){
....
Route=insertedRoute;
}
insertedRoute.LocationInRoute.Add(lInRoute );
}
참고 URL : https://stackoverflow.com/questions/6041057/multiple-added-entities-may-have-the-same-primary-key
'IT박스' 카테고리의 다른 글
현재 사용자가 관리자인지 확인 (0) | 2020.10.24 |
---|---|
JQuery / JavaScript로 링크 할 메일 호출 / 클릭 (0) | 2020.10.24 |
Firefox에 의해 표시되지 않는 파비콘 (0) | 2020.10.24 |
SQL Server에 파일 저장 (0) | 2020.10.24 |
Android Studio의 에뮬레이터가 시작되지 않음 (0) | 2020.10.24 |