简体   繁体   中英

Two many-to-one table relationships and insertion with Entity Framework

I have a model similar to this:

在此处输入图片说明

Context: The idea is that it's a database of samples. One sample has details, and several samples can be collated together into a CollatedSample, and the details can be collated together as well in a CollatedDetail. So, one CollatedSample has many CollatedDetails, and starts from many Samples, each of which has many Details. A CollatedDetail has many Details too. It's a "nice" square.

My approach to adding records is thus:

var sample = new Sample();
var detail = new Detail();
sample.Details.Add(detail);
// suppose I add a bit more meat to these entities...

var collatedSample = new CollatedSample();
var collatedDetail = new CollatedDetail();
collatedSample.Samples.Add(sample);
collatedSample.CollatedDetails.Add(collatedDetail);
collatedDetail.Details.Add(detail);

context.CollatedSamples.AddObject(collatedSample);
context.SaveChanges();

So I've added all elements to eachother, and added Detail to both Sample and CollatedDetail. On SaveChanges, I get an Update Exception with the jolly message:

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

What I think might really be happening is there is an attempt to record the Detail entity before the CollatedDetail is recorded. That Detail table, with its two relationships, is the one causing the trouble (not adding them to either Sample nor CollatedDetail confirms it). Perhaps there is a way to specify the order of insertion? I also tried the reverse, to set the parent instead of using .Add() on children collections, with the same result. Otherwise, how do I make this sort of 2-pronged insertion in one shot?

EDIT: tl;dr:

在此处输入图片说明

I found a workaround: I removed the Foreign Key between Detail and CollatedDetail like @JaderDiag suggested, and the reference field from the CollatedDetail table. Entity Framework creates partial classes, so it was easy to create other partial classes for both entities and manually join them. This will be much much slower, I suspect, but it provides the same fluidity in later exploitation as the entities would have provided with the foreign key.

This is a workaround, and definitely not the solution I was looking for. Would vote this down if I could.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM