views:

278

answers:

1

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!

A: 

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. Figure out which entity is causing the error and you'll see there's already another entity in the context with the same key.

Craig Stuntz