C# Unable to determine the principal end of the relationship

c# entity-framework


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

   newFile.Name = item.FileName;



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


foreach (var item in tempFilesList)


Because of this code, rows in theMyFile So, for instance, I see 6 rows if the loop iterates 3 times (3 x 2*).adapter.db.SaveChanges() ???)

But if I only have one,adapter.db.SaveChanges(); (That final one) I have a problem

Unable to identify the main end of the relationship for "my dbModel.FK MyFile File". The main key of many additional entities may be the same.

Since it doesn't commit the crime in that scenario, I presume it is becauseadapter.db.File.AddObject(newFile); before distributing them to theitem.MyFile.Add(new MyFile { FileID = newFile.FileID }); Though I might be mistaken; any suggestions for a solution?

8/9/2012 11:59:54 PM

Accepted Answer

You cannot usenewFile.FileID while creating a new oneMyFile before to saving modifications. Until you save the new object in the database, the FileID is default (0). You would need to utilize the navigation feature ofFile in theMyFile class. Data will be committed correctly when EF recognizes the relationship.

Change the line if you can.item.MyFile.Add(new MyFile { FileID = newFile.FileID }); with:

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

where File the definition of the navigation attribute inMyFile entity.

3/6/2018 6:58:06 AM

Popular Answer

This can be as a result of your EDMX's cyclical reference to the same database.

Meaning that you should check the EDMX to see whether the EmployeeDepartmentID is referred back to itself, for instance, if EmployeeDepartment is the table that you are trying to update and the Primary key is EmployeeDepartmentID and if it is an identity column and auto-generated. If so, remove it by performing a right-click on the reference in question.

This worked for me, and I really hope it does the same for you.



Related Questions


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