I'm reasonably new to EF, and struggling a little to facilitate deleting my objects. My two objects and associated DbContext look as follows:
public class Context: DbContext
{
public Context() : base(){}
public DbSet<Person> Persons {get;set;}
public DbSet<Vehicle> Vehicles {get;set;}
}
public class Person
{
public int PersonID {get;set;}
public string Name {get;set;}
}
public class Vehicle
{
public int VehicleID {get;set;}
public int? PersonID {get;set;}
[ForeignKey("PersonID")]
public virtual Person Person {get;set;}
}
As per above, one person can be linked to multiple vehicles. There is no explicit link from the person to the vehicle, but there is a link from the vehicle to a 'parent' person through the foreign key relationship.
I then create various vehicles in my code, and link these to optional person objects (foreign key is nullable).
My question is around deleting Person objects. I usually go about deleting the objects as follows:
private void DeletePerson()
{
using (var context = new Context())
{
int personID = 4; //Determined through other code
var person = context.Persons.Find(personID);
context.Persons.Remove(person);
context.SaveChanges();
}
}
The above code however would fail, giving me a reference constraint exception (due to the vehicle foreign key). I however would have expected the foreign key of all vehicles linked to the specific person to simply be set to null?
I was able to get the code to work by explicitly loading all relevant vehicles to the context as follows:
private void DeletePerson()
{
using (var context = new Context())
{
//Determined through other code
int personID = 4;
// Single vehicle associated with this person, there can be multiple vehicles
int vehicleID = 6;
var person = context.Persons.Find(personID);
// Seems to force loading of the vehicle, facilitating setting
// its "PersonID" property to null
var vehicle = context.Vehicles.Find(vehicleID);
context.Persons.Remove(person);
context.SaveChanges();
}
}
The problem with the above code however, is that I need to create a List object inside my Person class that contains a reference (or ID) to all potential dependent objects (vehicles is just one example here, there will be various other similar classes with similar relationships to Person).
Is the creation of this List in the Person object the only way of doing this? And is there some way of automating the creation of this list / automating the adding of the dependents? I'd prefer to not have to explicitly manage these relationships through a list object in my Person class.
Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…