I have some code that saves a many to many relationship in code. It was working fine with Entity Framework 4.1 but after updating to Entity Framework 5, it’s failing.
I’m getting the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint “FK_WebUserFavouriteEvent_Event”. The conflict occurred in database “MainEvents”, table “dbo.Event”, column ‘Id’.
I’m using POCO entities with custom mappings. Standard field and many-to-one relationship mappings seem to be working fine.
UPDATE
Ok, so I’ve got SQL Profiler installed and the plot has thickened…
exec sp_executesql N'insert [dbo].[WebUserFavouriteEvent]([WebUserId], [EventId])
values (@0, @1)
',N'@0 int,@1 int',@0=1820,@1=14
Which means:
WebUserId = @0 = 1820
EventId = @1 = 14
The interesting thing is is that EF5 seems to have flipped the foreign keys around… the WebUserId should be 14 and the EventId should be 1820, not the other way around like it is now.
I reviewed the mapping code and I’m 99% I’ve set it all up correctly. See Entity Framework Fluent API – Relationships MSDN article for more information.
NOTE: I have also found that this isn’t restricted to saving either, SELECTs are also broken.
Here’s all the relevant code:
Service Layer
public void AddFavEvent(WebUser webUser, Event @event)
{
webUser.FavouriteEvents.Add(@event);
_webUserRepo.Update(webUser);
}
Repository
public void Update<T>(params T[] entities)
where T : DbTable
{
foreach (var entity in entities)
{
entity.UpdatedOn = DateTime.UtcNow;
}
_dbContext.SaveChanges();
}
NOTE: I’m using a 1 DataContext per request approach, so webUser and @event would have been loaded from the same context as the one in the _webUserRepo.
Entities (don’t worry about DbTable stuff)
public class Event : DbTable
{
//BLAH
public virtual ICollection<WebUser> FavouriteOf { get; set; }
//BLAH
}
public class WebUser : DbTable
{
//BLAH
public virtual ICollection<Event> FavouriteEvents { get; set; }
//BLAH
}
Mappings
public class EventMapping : DbTableMapping<Event>
{
public EventMapping()
{
ToTable("Event");
//BLAH
HasMany(x => x.FavouriteOf)
.WithMany(x => x.FavouriteEvents)
.Map(x =>
{
x.MapLeftKey("EventId");
x.MapRightKey("WebUserId");
x.ToTable("WebUserFavouriteEvent");
});
}
}
public class WebUserMapping : DbTableMapping<WebUser>
{
public WebUserMapping ()
{
HasMany(x => x.FavouriteEvents)
.WithMany(x => x.FavouriteOf)
.Map(m =>
{
m.MapLeftKey("WebUserId");
m.MapRightKey("EventId");
m.ToTable("WebUserFavouriteEvent");
});
}
}
Looking at this I suspect that the problem might be caused by the fact that you map the same relationship twice. And you map it in different order.
I made a simple test where I first mapped the relationship once:
And then I changed the OnModelCreating to be:
What I found and suspected is that the first run generates this sql:
In constrast to the second which generates:
You see the values flipped? Here it actually count the ChildId column as ParentId. Now this doesn’t crash for me but I let EF create the database which means it probably just switch the column names and if I would look at the foreign keys they would be switched too. If you created the database manually that probably won’t be the case.
So in short: You mappings aren’t equal and I expect one of them to be used and that one is probably wrong. In earlier verions I guess EF picked them up in different order.
UPDATE:
I got a bit curious about the foreign keys and checked the sql.
From the first code:
And from the second code:
Now that is not nice. ParentId mapped against Children is certainly not what we want.
So is the second mapping wrong? Not really because see what happend when I removed the first one:
Somehow having two mappings seems to mess things up. Bug or not I don’t know.