user3343508
user3343508

Reputation: 89

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:

Is this not correct?

Upvotes: 4

Views: 4444

Answers (2)

user3343508
user3343508

Reputation: 89

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);

Upvotes: 4

rollo
rollo

Reputation: 305

For first you must make foreign key nullable.

Here is how

For second you will have to use the fluent API to do this.

Try adding the below to your DB Context

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

    modelBuilder.Entity<Person>()
        .HasOptional(a => a.Address)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
    }

For further detail see this link

Upvotes: 0

Related Questions