kad1r
5/3/2016 - 10:55 AM

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

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

Companies - Id, Heading, Description, Address, etc.
Customers - Id, CompanyId, FullName, Address, Phone, etc.

I'm using Repository with UnitOfWork, but you will see general entity framework dbcontext add and save method with commented.

for (int i = 0; i < 10; i++)
{
	var company = new COMPANIES
	{
		Id = i + 1, // we are just adding id for temp, don't worry database does not care of this. At the end you will see the results.
		Heading = "_company_name_" + i + 1,
		Description = "_test_description_" + i + 1,
		... // other fields that you need to fill
	};
	
	_uow.Repository<COMPANIES>()
		.Add(company);

	// db.COMPANIES.Add(company);
		
	for (int j = 0; j < 2; j++)
	{
		var customer = new CUSTOMERS
		{
			CompanyId = company.ID, // don't worry here too, because entity framework will get actual companyId from SaveChanges method.
			FullName = "_name_of_customer_" + j + 1,
			... // other fields that you need to fill
		};

		_uow.Repository<CUSTOMERS>()
			.Add(customer);
		
		// db.CUSTOMERS.Add(customer);
	}
}

_uow.SaveChanges();
// db.SaveChanges();