简体   繁体   中英

C# - EF 6 Abstract Navigation Property

I have the following abstract classes:

NotaFiscal:

public abstract partial class NotaFiscal
{   
    public virtual ICollection<NotaFiscalItem> NotaFiscalItens { get; set; }
}

NotaFiscalItem:

public abstract class NotaFiscalItem
{   
    ...
}

From which will be generated the concrete classes:

NotaFiscalEntrada:

public class NotaFiscalEntrada : NotaFiscal
{   
    public int NotaFiscalEntradaId { get; set; }
}

NotaFiscalEntradaItem:

public class NotaFiscalEntradaItem : NotaFiscalItem
{   
    public int NotaFiscalEntradaItemId { get; set; }
}

The question: The navigation property in the abstract class NotaFiscal is an collection of abstract objects, is there a way to navigate in the concrete class NotaFiscalEntrada to the objects in the collection, which will be concrete too - NotaFiscalEntradaItem ? Is there a way to tell that in the concrete class NotaFiscalEntrada the ICollection of NotaFiscalItem will be the NotaFiscalEntradaItem and EF will understand this and navigate to it?

I gotta use it this way because the intelligence of the collection (LINQ queries, sum...etc..) is all in the abstract class, and others classes like NotaFiscalSaida and NotaFiscalItemSaida will be created from the abstract classes. Each one will be a table in the DB.

I'm using Code First, POCO, EF 6.1 and TPC mapping.

Entity Framework does not support Generic Entities, but it does support Entities that are inheriting generic classes

Try to change your abstract NotaFiscal class to have a generic parameter to represent each NotaFiscalItem :

public abstract class NotaFiscal<T> where T : NotaFiscalItem
{
    public abstract ICollection<T> NotaFiscalItems { get; set; }
}

Then in your concrete classe:

public class NotaFiscalEntrada : NotaFiscal<NotaFiscalEntradaItem>
{
    public int NotaFiscalEntradaId { get; set; }

    public override ICollection<NotaFiscalEntradaItem> NotaFiscalItems { get; set; }
}

This way, your concrete NotaFiscal types will be able to expose their concrete NotaFiscalItem collection using the NotaFiscalItems property of each.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM