EF Core Include multiple inherited types TPH

依然范特西╮ 提交于 2019-12-13 00:14:39

问题


The problem

Query BaseClass and Include information from derived types.

For example: Base class Offer has two types one with a Card only (CardOffer) and with Multiple Cards (CarouselOffer).

Question: How to query the BaseClass and Include the information from the derived types CardOffer and CarouselOffer? In the manner shown below:

    _dbContext.Offers.Include(...).ToList();

Currently I solved this by querying each inherited type

        var cards = await _dbContext.CardOffers
            .Include(c => c.Card)
            .ToListAsync();

        var carousels = await _dbContext.CarouselOffers
            .Include(c => c.Cards)
            .ToListAsync();

        List<Offer> offers = new List<Offer>();
        offers.AddRange(cards);
        offers.AddRange(carousels);

But this is far from optimal.

Additional Information: Below I added a diagram to show the Database and my code sample:

The Code:

Offer class

public abstract class Offer
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public string Status { get; set; }

    public string Discrimnator { get; set; }

    public ClientUser ClientUser { get; set; }
}

CardOffer class:

public class CardOffer : Offer
{
    public Card Card { get; set; }
}

CarouselOffer class:

public class CarouselOffer : Offer
{
    public ICollection<Card> Cards { get; set; }
}

Card class:

public class Card
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public string Title { get; set; }

    public string ImageUrl { get; set; }

    public string Description { get; set; }

    public string Category { get; set; }

    public ICollection<Button> Buttons { get; set; }
}

FluentApi:

        modelBuilder.Entity<ClientUser>()
            .HasMany(u => u.Offers)
            .WithOne(u => u.ClientUser)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<Offer>()
            .HasDiscriminator<string>("Discrimnator");

        modelBuilder.Entity<CardOffer>()
            .HasOne(u => u.Card);

        modelBuilder.Entity<CarouselOffer>()
            .HasMany(u => u.Cards);

来源:https://stackoverflow.com/questions/49609506/ef-core-include-multiple-inherited-types-tph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!