I’ve been tinkering a bit with the option to include foreign keys in the model generated by Entity Framework (from an existing MSSQL database).
Let’s assume I have a model of Person and Company, and I want to create both at the same time. Where Companies can have multiple Persons. Person has Id, Name, CompanyId, and Company has Id and Name.
I’m not quite sure of how I’m supposed to create new objects that are related to each other. One way I’ve sort of figured out is the following:
// Company needs ID and Name, and ID is auto generated, so -1
Model.Company newCompany = Model.Company.CreateCompany(-1, "Test Inc");
// Person needs ID, Name and a CompanyID. What is CompanyId supposed to be?
Model.Person newPerson = Model.Person.CreatePerson(-1, "John Doe", -1);
// And to actually get the Company relation going
newPerson.Company = newCompany;
Followed by adding it to the context and saving.
Now, this works, but I’m not sure this is what I’m supposed to do?
Because, if we instead imagine that I would abstract the creations of these (Which is what I have in most parts of my application). And that maybe we have the following function, I still have to supply the ID, even though the EntityState of this object is unknown. It could have an ID for all I know, not all companies are new companies. So I can’t just do this:
public static Model.Person CreatePerson(string name, Model.Company company) {
Model.Person newPerson = Model.Person.CreatePerson(-1, name, company.Id);
return newPerson;
}
But in the case that company is a newly added object, this will fail. And as such, am I correct in believing that using actual ID’s in the Create-method is useless? Because unless I check entity state, I’ll just end up having to do the following:
public static Model.Person CreatePerson(string name, Model.Company company) {
Model.Person newPerson = Model.Person.CreatePerson(-1, name, -1);
newPerson.Company = company;
return newPerson;
}
I realize the benefit of using a foreign key ID to create an object in the cases where you have the ID but not the object, and you don’t actually need to fetch the whole object from the database. But I’m thoroughly confused about how to best go about this thing.
You probably must set both the foreign key property and the navigation property to cover both cases of a new
Companyand an existing one in your method:companyis new EF will ignore thenewPerson.CompanyIdvalue and create the relationship based on the navigation propertynewPerson.Companyonly.companyis existing (in stateUnchangedorModified) the FK propertynewPerson.CompanyIdmust match the primary key valuenewPerson.Company.Id, otherwise you’ll get an exception.