简体   繁体   English

多个添加的实体可能具有相同的主键

[英]Multiple added entities may have the same primary key

Here is my model of 3 entities: Route, Location and LocationInRoute. 这是我的3个实体模型:Route,Location和LocationInRoute。
模型

the following method fails and get exception when commit it: 以下方法失败并在提交时获取异常:

 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;
        }

When doing: 进行时:

InsertRouteIfNotExists(companyId, locations);
UnitOfWork.Commit();

I got: 我有:

Unable to determine the principal end of the 'SimTaskModel.FK_T_STF_SUB_LOCATION_IN_ROUTE_T_STF_LOCATION_location_id' relationship. 无法确定“ SimTaskModel.FK_T_STF_SUB_LOCATION_IN_ROUTE_T_STF_LOCATION_location_id”关系的主要结尾。 Multiple added entities may have the same primary key. 多个添加的实体可能具有相同的主键。

When splitting the commit and insert in into the methos - it 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. 我想在方法外调用一次commit。 Why it fails in the first example and what does this exception means? 为什么在第一个示例中失败,该异常意味着什么?

The error is caused by a foreign key ID (as opposed to a reference) which cannot be resolved. 该错误是由无法解析的外键ID(而不是引用)引起的。 In your case, you have a LocationInRole that references a Location with an ID of 0. There are multiple Locations with this ID. 在您的情况下,您有一个LocationInRole引用一个ID为0的位置。有多个具有此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. 尚未为位置分配ID,因为尚未将其保存到生成ID的数据库中。 In your second example, the Locations are saved before their IDs are accessed which is why this works. 在第二个示例中,在访问位置ID之前先保存位置,这就是为什么这样做的原因。

You will not be able to rely on the Location IDs to define the relationships if you want to SaveChanges only later. 如果您只想稍后保存更改,则将不能依靠位置ID来定义关系。

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. 然后,这些关系将基于不依赖于LocationID的对象引用。

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. 换句话说,在Question中,ParentLocation / ParentLocationId是对该表的递归引用。

The ParentLocationId is not Nullable. ParentLocationId不可为空。 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. 这意味着它将插入一个0,并且EF将在插入时(而不是在您进行迁移时)进行抱怨-即使事实是一旦运行Migration,您就有一个表EF永远不会让您插入。

The only way to make a recursive reference back to the same table work is to make the recursive reference nullable: 使递归引用返回到同一表工作的唯一方法是使递归引用可为空:

public class Location
{
    public int Id { get; set; }
    ...
    public Location ParentLocation { get; set; }
    [ForeignKey("ParentLocation")]
    public int? ParentLocationId { get; set; }
}

Note the ? 注意? after the int . int

For those searching for this exception: 对于那些搜索此异常的人:
In my case, it was failing to set a required navigation property. 就我而言,它无法设置必需的导航属性。

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

i had same problem. 我有同样的问题。 with below scenario solved for me. 以下情况为我解决了。 i think you must change your code such as below: 我认为您必须更改您的代码,如下所示:

var insertedRoute =routeRep.Insert(route);
.....
insertedRoute.LocationInRoute = new List<LocationInRoute>();
for(....){
    var lInRoute = new LocationInRoute(){
    ....
    Route=insertedRoute;
}

insertedRoute.LocationInRoute.Add(lInRoute );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EF6:多个添加的实体可能具有相同的主键 - EF6: Multiple added entities may have the same primary key 多个添加的实体可能在实体框架中具有相同的主键 - Multiple added entities may have the same primary key in Entity Framework 多个添加的实体可能在数据库种子上具有相同的主键 - multiple added entities may have the same primary key on database seed 无法确定 X 关系的主端。 多个添加的实体可能具有相同的主键 - Unable to determine the principal end of the X relationship. Multiple added entities may have the same primary key 对于某些循环实体,多个添加的实体可能具有相同的主键 - multiple added entities may have the same primary key for some cyclic entity 实体框架6.1:添加的多个实体可能具有相同的主键 - Entity Framework 6.1: Multiple added entities may have the same primary key 无法确定关系的主要终点,多个添加的实体可能具有相同的主键 - Unable to determine the principal end of the relationship, Multiple added entities may have the same primary key EF 6.多个添加的实体可能具有相同的主键。 错误 - EF 6. Multiple added entities may have the same primary key. Error 无法确定etaxiDataModel关系的主要结尾。 多个添加的实体可以具有相同的主键 - Unable to determine the principal end of the etaxiDataModel relationship. Multiple added entities may have the same primary key 无法确定“ Vehicle_VehicleClass”关系的主要结尾。 多个添加的实体可能具有相同的主键 - Unable to determine the principal end of the 'Vehicle_VehicleClass' relationship. Multiple added entities may have the same primary key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM