简体   繁体   English

实体框架:使用一对一引用插入

[英]Entity Framework: insert with one-to-one reference

I'm having a bit trouble inserting into a mssql database using Entity Framework. 我在使用实体框架插入mssql数据库时遇到了一些麻烦。 There's two tables that I want to insert into, where one of table 1s fields is a foreign key in table2. 我要插入两个表,其中表1s字段之一是table2中的外键。

This is the code I have so far: 这是我到目前为止的代码:

Media media = null;
foreach(POI p in poiList)
{
    media = new Media() 
    {
        Path = p.ImagePath,
        Title = p.Title
    };

    if (media != null && !context.Media.Any(me => me.Title == p.ImageTitle))
    {
        context.AddToMedia(media);
        context.SaveChanges();
    }

    PointOfInterest poi = new PointOfInterest()
    {
        Altitude = 2000.0,
        ID = p.ID,
        Latitude = p.Latitude,
        Longitude = p.Longitude,
        LatitudeRoute = p.LatitudeRoute,
        LongitudeRoute = p.LongitudeRoute,
        Description = p.Description,
        Title = p.Title,
        DefaultImageID = media.ID,
    };    
    context.AddToPointOfInterest(poi);
}
context.SaveChanges();

The following gives me this error: 以下给我这个错误:

An object with the same key already exists in the ObjectStateManagerAn object with the same key already exists in the ObjectStateManager 具有相同键的对象已存在于ObjectStateManager中具有相同键的对象已存在于ObjectStateManager中

I'm still learning how to use the entity framework, so I don't even know if this would be the right approach to insert into two referenced tables. 我仍在学习如何使用实体框架,所以我什至不知道这是否是插入两个引用表中的正确方法。

Can anyone enlighten me on this? 有人可以启发我吗? :) Any help would be greatly appreciated! :) 任何帮助将不胜感激!

Thanks! 谢谢!

It means just what the error says. 这就是错误的含义。 You have a primary key violation. 您有一个主键冲突。 You can only call Context.AddTo... once with a given key value. 您只能使用给定的键值调用Context.AddTo... Figure out which entity is causing the error and you'll see there's already another entity in the context with the same key. 找出导致错误的实体,您会发现上下文中已经存在另一个具有相同键的实体。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM