I'm using EF4 with POCO and the code below is what I have to update a license. I only pasted here the section of the code that is relevant to the problem, which is adding LicenseDetails.
The problem is that for each LicenseDetail that are inserted, EF also unexpectadly adds rows to the "Item" lookup table. Why?!
The relationship of both tables defined in the database (SQLServer 2008) is shown below and I do Database first, therefore EF generates the entities' relationship based on this.
ALTER TABLE [dbo].[LicenseDetail]
WITH CHECK ADD CONSTRAINT [FK_LicenseDetail_Item] FOREIGN KEY([ItemId])
REFERENCES [dbo].[Item] ([Id])
GO
ALTER TABLE [dbo].[LicenseDetail] CHECK CONSTRAINT [FK_LicenseDetail_Item]
GO
the update method:
public static void UpdateLicense(License license)
{
using (ALISEntities context = new ALISEntities())
{
context.ContextOptions.ProxyCreationEnabled = true;
var storedLicense =
context.Licenses.Include("LicenseDetails")
.Where(o => o.Id == license.Id).SingleOrDefault();
//////////////////////////////////////////////////////////////
// license details to add
List<LicenseDetail> toAdd = new List<LicenseDetail>();
foreach (LicenseDetail ld in license.LicenseDetails)
{
if (storedLicense.LicenseDetails
.Where(d => d.ItemId == ld.ItemId).Count() == 0)
{
toAdd.Add(ld);
}
}
toAdd.ForEach(i => storedLicense.LicenseDetails.Add(i));
context.SaveChanges();
}
}