I have 3 entities
- Printer
- Server
- Driver
The Printer has Server and Driver properties
Somwhere in my code I've set up an IEnumerable<Printer> where each instance of printer holds it's own Server and Driver entities.
Now when I'm trying to submit it to the db, I'm using following code:
foreach (Printer p in printers)
{
printmanEntities _dc = new printmanEntities();
p.Driver = _dc.DriverSet.FirstOrDefault(d => d.Name == p.Driver.Name) ?? p.Driver;
p.Server = _dc.ServerSet.FirstOrDefault(s => s.Name == p.Server.Name) ?? p.Server;
_dc.AddToPrinterSet(p);
_dc.SaveChanges();
}
It is supposed that I'll get a record for each Printer object, and a single record for each unique Driver and Server name. But actual result is quite wired.
Code above produces a single record for each unique Driver object, but for no obvious reason creates more than one record for each unique Server. And all Printer records point to single Server record.
Furthermore if I assign p.Server first, then I get only unique records for server entities but multiple records for Driver entities.
What am I doing wrong?
Update: Replaced EF with LINQ2SQL and it worked just as i expected. A single row for each unique entity, nothing more.