Our database has three entities: Person
, Company
and PhoneCall
.
Person
describes an individual. Company
describes a company. PhoneCall
describes the details of a phone call to either a Person
or Company
.
public class Person
{
public int Id { get; set;}
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class Company
{
public int Id { get; set;}
public string Name { get; set; }
public string VatNumber { get; set; }
}
public class PhoneCall
{
public int Id { get; set;}
public string Description { get; set;}
public int Duration { get; set;}
public int? PersonId { get; set; }
public Person Person { get; set; }
public int? CompanyId { get; set; }
public Company Company { get; set; }
}
I am seeing certain undesirable behavior with Entity Framework when deleting a Person
or Company
.
If I delete a Person
, entity framework is updating any associated PhoneCall
entries and setting PersonId
to NULL.
dbContext.Entry(person).State = EntityState.Deleted;
dbContext.SaveChanges();
Instead of Entity Framework setting PersonId
to null on all of the associated PhoneCall
entries, what I would like is for entity framework throw some kind exception to let me know that the Person
cannot be deleted because there are related entities referencing said Person
.
The problem seems to be that entity framework doesn't respect the PhoneCall.PersonId
and PhoneCall.CompanyId
foreign keys since they are both (necessarily) nullable.
I can obviously perform my own check before deletion like so:
if (phoneCallDbSet.Where(ph => ph.Person == personToDelete).Any())
throw new InvalidOperationException("Cannot delete person with associated calls");
...but my preference would be to set up a some kind of restriction that prevents Entity Framework from setting the foreign key to NULL in the first place, so that if a developer forgets to perform this check, we don't end up with entries in the PhoneCall
table linking to nothing.
Is this possible?
No!! There is no way to achieve what you want without having explicit checks in your code.
If we set the property as nullable, we tell the framework that you can set it to null if required. Then why would it show any error when it is set to null?
Either you make the property non-nullable or have explicit checks in your code to handle it.
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.