本文介绍了实体框架-具有.Include的继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这里也有类似的帖子,但不完全相同...



我的EF模型中有两个实体-我们称其为Person



我在Developer上也有一个名为Qualifications的协会。这在Person实体上不可见。



如果我要根据上下文编写查询,如何自动.include()开发人员的资格,例如



来自上下文中的员工。员工
包括(资格)
选择员工



不起作用... EF抱怨该关系不存在(我想是因为它在Employee上不存在-但是上下文中没有开发人员实体,只有Employee)。

解决方案

我遇到了这个问题并做了一些实验。这是我发现使用LINQ 2实体的工作。



在您的示例中,我们说的是Person<-开发人员----资格。
$ b

如果您想选择一个具有资格的开发人员,则可以这样做。

  var dev =(从d在context.Persons.OfType< Developer> 
.Include( Qualifications)
其中d.ID == id
选择d).FirstOfDefault();

现在可以说我们在Person和Address之间还有另一个关联,我们也可以将Address包含在select中使用LINQ 2实体。

  var dev =(从d上下文中。人员
.Include( Address)
.OfType< Developer>()
.Include( Qualifications)
其中d.ID == id
选择d).FirstOfDefault();

请注意,在转换类型之前,我是如何包括我需要的东西的;在转换之后,还包括了我的内容。这两个组件现在应该一起工作,没有任何问题。我已经测试了这些方法,它们都可以工作。希望您可以正确设置继承设置,希望它们对您有用。



GL。


I think that there's a similar post on here about this but not exactly the same...

I have two entities in my EF model - let's call them Person and Developer, with the latter inheriting from the former.

I also have an association on Developer called Qualifications. This is not visible on the Person entity.

If I'm writing a query against the context, how do I automatically .Include () the Qualifications of the Developer e.g.

from employee in context.Employee.Include ("Qualifications")select employee

doesn't work... EF complains that the relationship does not exist (I assume because it does not exist on Employee - but there's no Developer entity on the context, just Employee).

解决方案

I've come across this problem and experimented a little. Here is what i found worked using LINQ 2 Entity.

Say we have in your example Person <-- Developer ---- Qualifications.

If you would like to select a Developer with Qualifications included, you would do this.

var dev = (from d in context.Persons.OfType<Developer>
                            .Include("Qualifications")
          where d.ID == id
          select d).FirstOfDefault();

Now lets say we have another association between Person and Address, we can also include Address into the select also using LINQ 2 Entity.

var dev = (from d in context.Persons
                            .Include("Address")
                            .OfType<Developer>()
                            .Include("Qualifications")
          where d.ID == id
          select d).FirstOfDefault();

Notice how I have included the things I needed before I converted the Type and also included again after the conversion. Both includes should now work together without any problems. I have tested these methods and they both work. I hope they work for you given you have your inheritance setup correctly.

GL.

这篇关于实体框架-具有.Include的继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 14:22