EF Core包含多个继承类型TPH

时间:2018-04-02 10:25:12

标签: entity-framework ef-code-first entity-framework-core ef-core-2.0

问题

查询BaseClass并包含派生类型的信息。

例如:基类优惠有两种类型,只有一张卡片( CardOffer )和多张卡片( CarouselOffer )。

问题:如何查询BaseClass并包含派生类型CardOffer和CarouselOffer中的信息?按以下方式显示:

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

目前我通过查询每个继承的类型

解决了这个问题
        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);

但这远非最佳。

其他信息:下面我添加了一个图表来显示数据库和我的代码示例: DB Diagram

守则:

优惠

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 类:

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

CarouselOffer 类:

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

类:

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);

0 个答案:

没有答案