C# Unable to determine the principal end of the relationship

c# entity-framework

Question

foreach (var item in order.MyFiles)
{
   var newFile = adapter.db.File.CreateObject();

   newFile.Name = item.FileName;

   adapter.db.File.AddObject(newFile);

   adapter.db.SaveChanges();

   item.MyFile.Add(new MyFile { FileID = newFile.FileID });

   adapter.db.SaveChanges();
}

foreach (var item in tempFilesList)
{
    adapter.db.DeleteObject(item);
}

adapter.db.SaveChanges();

That code duplicates rows in the MyFile table, e.g if the loop iterates 3 times I see 6 rows (3 x 2*adapter.db.SaveChanges() ???)

But, if I just have only one adapter.db.SaveChanges(); (that last one) I get the error

Unable to determine the principal end of the 'my_dbModel.FK_MyFile_File' relationship. Multiple added entities may have the same primary key.

I suppose it is caused that in that case it doesn't commit the adapter.db.File.AddObject(newFile); items before assinging them to the item.MyFile.Add(new MyFile { FileID = newFile.FileID }); But I can be wrong, any ideas how to fix it?

1
33
8/9/2012 11:59:54 PM

Accepted Answer

You cannot use newFile.FileID when defining a new MyFile before saving changes. The FileID is default (0) until you save the new entity in database. You'd have to use navigation property of File in your MyFile class. EF will detect the relation and will commit data appropriately.

Try to change the line item.MyFile.Add(new MyFile { FileID = newFile.FileID }); with:

item.MyFile.Add(new MyFile { File = newFile });  

where File is the navigation property defined in MyFile entity.

51
3/6/2018 6:58:06 AM

Popular Answer

This could be because of a cyclic reference in you EDMX back to the same table.

Means for example if EmployeeDepartment is the table that you are going to update and the Primary key is EmployeeDepartmentID and if it is identity column and auto-generated, Check in the EDMX whether the EmployeeDepartmentID is referenced back to itself. If so, right click on that foreigh key reference and click delete.

This worked for me and I hope this works for you as well.

Thanks,

Bibin.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow