查询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);
但这远非最佳。
优惠类
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);