在asp.net中访问EF的继承实体

时间:2022-09-18 08:49:44

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

我开始使用EF(6.0)并提出一个简单的问题:

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".

我使用模型第一种方法来设计包含名为“Component”的实体的实体模型。然后我创建了几个从这个基类型继承的实体,例如“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

现在在我的ASP.net代码中,我可以访问context.Components,但我似乎无法直接返回context.VideoCards。因此,如果我只想返回一个视频卡列表,我应该使用类似的东西

 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.

在此先感谢您的回复。

1 个解决方案

#1


1  

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

您可以在上下文中公开VideoCards属性,并通过它只获取VideoCard实体。

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

#1


1  

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

您可以在上下文中公开VideoCards属性,并通过它只获取VideoCard实体。

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