the correct way to map identity base class with fluent api in ef core?

c# ef-core-2.0 ef-fluent-api entity-framework-core

Question

How is it supposed that i have to map the identity base class in EF Core if i want to entity be a primary key

I based in the project example of Vaughn Vernon (example) in this example him create a identity class like that:

public class ProductId : Identity
{
    public ProductId()
        : base()
    {
    }

    public ProductId(string id)
        : base(id)
    {
    }
}

and here is his implementation

public class Product {
  public ProductId ProductId {get; private set;}
}

My doubt is what is the correct way to map this? because i was try to map directically modelBuilder.Entity<Product>().HasKey(p => p.ProductId); but in migration EF Core tell me

Cannot call Property for the property 'ProductId' on entity type 'Product' because it is configured as a navigation property. Property can only be used to configure scalar properties.

i know that i can use OwnsOne but if i do that way i will don't create a primary key of identity, right?

1
0
3/13/2018 6:04:58 PM

Popular Answer

Your objects should look like the following

Object Class

public class Product
  {
    public int Id { get; set; }
    public string Name { get; set; }
    ...
  }

By default entity framework will look for an object named Id or ProductId and will automatically make it the primary key. So while it is not needed to set the key in the DbContext you are able to do it. I generally do not set the Id unless it is a different name.

DbContext

protected override void OnModelCreating(ModelBuilder builder)
    {
      base.OnModelCreating(builder);
      builder.Entity<Product>().HasKey(x => x.Id);
    }

** UPDATE **

If you are not setting the DbSets in your db context, then you indeed will have to set the id in the OnModelCreating call so the migrations will recognize the object as an Entity object

0
3/4/2018 7:47:03 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