问题
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