Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework, Code First: How can i make a Foreign Key Not-Nullable

All possibilities to change the database model with Fluent API i found so far assume that the property which i want to edit exist also as a property in the entity. But i don't know how to change attributes of a property, which is not a property in the entity class.

Example:

public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public List<Address> Addresses { get; set; }

    public Person()
    {
        this.Addresses = new List<Address>();
    }
}
public class Address
{
    public int AddressId { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

Now Code First creates a database where the Addresses table has PersonId as a FK, so having a 1-to-* relationship (what is what i want). But the FK PersonId in Addresses is nullable, and i can't access this FK in Fluent API since there is no property. How can i change this FK to be not-nullable?

Also, at the moment when i want to delete a Person, EF don't let me do this since there is an associated address. I thought the behaviour is:

  • nullable FK: delete the record in question, set the child record FK to null
  • not-nullable: error, or delete record together with all associated records (depending on cascade rules)

Is this not correct?

like image 567
user3343508 Avatar asked Sep 17 '25 03:09

user3343508


1 Answers

The following Fluent API directive did it for me, so to achieve

  • 1-to-* relationship
  • FK not nullable
  • FK not defined as a property in the entity class
  • cascade delete (deleting the parent deletes all associated records, here Addresses)

the following statement has to be included in OnModelCreating

modelBuilder.Entity<Person>().HasMany(a => a.Addresses).WithRequired().WillCascadeOnDelete(true);
like image 171
user3343508 Avatar answered Sep 19 '25 17:09

user3343508