user1275154
user1275154

Reputation: 1150

EF inserts Child before Parent Entity, throws conflicted with the FOREIGN KEY constraint

I'm inserting (adding new) child and parent entities in single SaveChanges(), and EF decided to insert the child first (referencing parent, can see the insert statement in the profiler), which obviously throws

The INSERT statement conflicted with the FOREIGN KEY constraint... :

[DriverStat].DriverId -> [Driver].Id

driverId = Guid.NewGuid();
//parent
var dr = new Driver()
{
    Id = driverId,
    Name = "John",
};
db.Drivers.AddObject(dr);

//child
var driverMainStats = new DriverStat()
{       
    Driver = dr //parent reference. Same problem if FK DriverId = driverId is used        
};

db.DriverStats.AddObject(driverMainStats);

db.SaveChanges();

Since the Driver 'dr' that DriverStat is referencing does not exist yet.

Any idea why EF would be wanting to insert the child entity (DriverStat) before the parent (Driver)? Is there a way of telling EF to do the right thing?

Any ideas? Stevo

EDIT: Problem solved. After running the latest ddl, I was accidently missing the foreign keys between those two tables, that resulted in EF not caring about the order. Sorry for false alarm

Upvotes: 1

Views: 849

Answers (2)

user1275154
user1275154

Reputation: 1150

Problem solved. After running the latest ddl, I was accidently missing the foreign keys between those two tables, that resulted in EF not caring about the order. Sorry for false alarm

Upvotes: 1

Komengem
Komengem

Reputation: 3764

If both objects are being created at the same time, or if you just want to initialize child object, try this:

driverId = Guid.NewGuid();
//parent
var dr = new Driver()
{
    Id = driverId,
    Name = "John",

    //child
    DriverStat = new DriverStat()
    {       
        //Add stuff here, no need to do this (Driver = dr)
    }
};
db.Drivers.AddObject(dr);

db.SaveChanges();

Assuming that you have something like

public virtual DriverStat DriverStat { get; set; } in Driver class and

public virtual Driver Driver { get; set; } in DriverStat class

Upvotes: 2

Related Questions