How to apply inheritance in the Entity Framework

0

I am working on a Windows Forms desktop app, I use Visual Studio 2015, Entity Framework approach code-firts.

The subject is the following: I have some tables such as: Purchases, Sales, TypeOperations and Movements.

In TipoOperacoines register the following data: Sale, Purchase, Consignment, Promotion, Prize, Donation, etc. and this is related to Movements.

I have related Sales and Purchases to Movements, but SellId and BuyId in Movements are an optional relation (means that allows null).

I show a data model because the UML I have is a bit extensive. The question is: How can I apply inheritance in this case? I use Entity Framework code-firts

    
asked by Pedro Ávila 25.08.2016 в 00:30
source

1 answer

1

To define the inheritance you can use the TipoOperacionId field as a discriminator.

[Entity Framework] [Code First] Inheritance - Table by hierarchy - Table per Hierarchy (TPH)

in the article you will see how a Type field is defined that fulfills this function.

In the mapping you define the inheritance by indicating the field that will allow you to define the type of the entity, this value can be numeric.

Map<EmployeeInternal>(x => x.Requires("Type")
                             .HasValue("I")
                             .HasColumnType("char")
                              .HasMaxLength(1));

Map<EmployeeExternal>(x => x.Requires("Type")
                              .HasValue("E"));

One detail is that although in your case you derfines a table of types, you are going to have to indicate in a fixed way in code what discriminative value represents each type in particular.

You will also have to define the classes for each type you support.

public class Movimiento
{
    public string Usuario {get;set;}
    public DateTime Fecha {get;set;}
}

public class MovimientoVenta : Movimiento
{
    public int? VentaId {get;set;}
    public Venta Venta {get;set;}
}

public class MovimientoCompra : Movimiento
{
    public int? CompraId {get;set;}
    public Compra Compra {get;set;}
}
    
answered by 25.08.2016 / 04:55
source