thankyoussd
thankyoussd

Reputation: 65

Accessing inherited entities of EF in asp.net

I'm getting started on EF (6.0) and have a quick question:

I used the model first approach to design an entity model that includes an entity named "Component". I then created several entities that inherited from this base type, such as "VideoCard".

Now in my ASP.net codes, I have access to context.Components, but I cannot seem to directly return context.VideoCards. So if I want to return a list of video cards only, should I use something like

 context.Components.OfType<VideoCard>();

(tried this it seems to work), or is there something else I should know on this topic?

Edit: I realized that this also works:

context.Components.Where(x => x is VideoCard);

Is one of these approaches better than the other?

Thanks in advance for your reply.

Upvotes: 3

Views: 66

Answers (1)

Oleksandr Kobylianskyi
Oleksandr Kobylianskyi

Reputation: 3380

You can expose VideoCards property in you context and get only VideoCard entities via it.

public class MyContext
{
  public DbSet<Component> Components { get; set; }
  public DbSet<VideoCard> VideoCards { get; set; }
}

And use it like below

var allVideoCards = context.VideoCards.ToArray();

Upvotes: 1

Related Questions