EF Core 2.0 One to one - what's the deal?

c# entity-framework-core

Question

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.

1
1
12/8/2018 4:45:50 AM

Popular Answer

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.

owned-entities article

2
12/8/2018 4:12:10 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow