Map property using OwnsOne method in EF Core 2.0

.net-core entity-framework entity-framework-core

Question

I'm trying to migrate EF 6 project to EF Core 2.0. I would like to streess out that I am not allowed to change anything in database structure - must be exactly the same as for EF 6 project.

I have the foloowing entities:

abstract class Vehicle { ... }

abstract class Car : Vehicle 
{ 
    public Dimension Dimensions { get; set; } 
}

class Audi : Car { ... }

class Mazda : Car { ... }

class Dimension
{
    public double Width { get; set; }
    public double Height { get; set; }
}

Table mappings as follows:

public VehicleMap(EntityTypeBuilder<Vehicle> entityBuilder)
{
    entityBuilder.ToTable("Vehicles");
    entityBuilder.HasKey(_ => _.Id);
    entityBuilder.HasDiscriminator<string>("Type").HasValue<Truck>(nameof(Truck));
}

public CarMap(EntityTypeBuilder<Car> entityBuilder)
{
    entityBuilder.HasDiscriminator<string>("Type")
        .HasValue<Mazda>(nameof(Mazda))
        .HasValue<Audi>(nameof(Audi));

    **entityBuilder.OwnsOne(_ => _.Dimensions);**
}

The problem I have is about Dimensions property defined in Car abstract class. I would like to map it using OwnsOne method to have all its class properties defined in the same table.

I'm getting the following error:

Cannot use table 'Vehicles' for entity type 'Car.Dimensions#Dimension' since it has a relationship to a derived entity type 'Car'. Either point the relationship to the base type 'Vehicle' or map 'Car.Dimensions#Dimension' to a different table.

Any idea how to solve it in EF Core 2.0?

1
3
9/3/2017 9:10:21 AM

Popular Answer

The Dimension known as ValueObject. The best practice for this type of objects is here.

To implement this objects in your context first you should define it in base table, since when you create database with this configuration you have just one table with the name of Vehicles and discriminator column with the name of Type.

As the error say:

Either point the relationship to the base type 'Vehicle'

we should define Dimension in base class.

abstract class Vehicle 
{
    public Dimension Dimensions { get; private set; } 
}

Table mappings:

public VehicleMap(EntityTypeBuilder<Vehicle> entityBuilder)
{
    entityBuilder.ToTable("Vehicles");
    entityBuilder.HasKey(_ => _.Id);
    entityBuilder.HasDiscriminator<string>("Type").HasValue<Truck>(nameof(Truck));
    // Here
    entityBuilder.OwnsOne(p => p.Dimensions);
}
0
1/7/2018 5:59:41 PM


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