Entity Framework: insert with one-to-one reference

Posted by bomortensen on Stack Overflow See other posts from Stack Overflow or by bomortensen
Published on 2010-04-27T10:08:53Z Indexed on 2010/04/27 10:13 UTC
Read the original article Hit count: 643

Hi 'overflow!

I'm having a bit trouble inserting into a mssql database using Entity Framework. There's two tables that I want to insert into, where one of table 1s fields is a foreign key in 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

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!

© Stack Overflow or respective owner

Related posts about c#

Related posts about entity-framework