I don't think what I'm trying to do is crazy. I have a Person entity that will have one address. I don't want to have the PersonId
as a property in my Address entity. When I try to save to the database though EF Core keeps giving me an error on not being able to insert NULL into the PersonId
column on Address table.
public class Person
{
public int Id { get; private set;}
public string Name { get; private set;}
public Address Address { get; private set;}
// .. constructor etc
}
public class Address
{
public int Id { get; private set;}
public string Street { get; private set;}
// .. constructor etc
}
Database Tables:
Person: Id, Name
Address: Id, Street, PersonId
Or do I need to have reference navigation properties at both sides, which seems really silly to have to do.
If you have 1:1 person:address you can use Value object as well. Its awesome.
Your main object registered in your DbContext for EF
public DbSet<Person> Persons { get; set; }
public class Person
{
public int Id { get; private set;}
public string Name { get; private set;}
public Address address { get; private set;}
// .. constructor etc
}
And your Address object as Value object with attribute [Owned]
[Owned]
public class Address
{
public int Id { get; private set;}
public string Street { get; private set;}
}
and then set mapping in DbContext OnModelCreating
modelBuilder.Entity<Person>().OwnsOne(o => o.Address);
EF will generate your value object into Person table but in your application you will have two objects.