LINQ中导航属性查询的ArgumentException [英] ArgumentException on navigation property query in LINQ
问题描述
在使用Entity Framework 6的Visual Studio 2015 WPF应用程序中,我具有以下LINQ查询:
I have the following LINQ query in a Visual Studio 2015 WPF app using Entity Framework 6:
var query = Context.Services.AsQueryable();
Services
实体具有以下导航属性:
The Services
entity has the following navigation property:
public virtual ICollection<ServiceStatu> ServiceStatus { get; set; }
一个服务可以有0个或多个ServiceStatus.我正在尝试使用Include
来获取状态等于7的服务:
A Service can have 0 or many ServiceStatus. I'm trying to use Include
to fetch services with status that equal 7:
query = query.Include(x => x.ServiceStatus.Where(p => p.serviceStatusID == 7));
但是它抛出了这个异常:
But it's throwing this exception:
EntityFramework.dll中发生了'System.ArgumentException'类型的异常,但未在用户代码中处理
An exception of type 'System.ArgumentException' occurred in EntityFramework.dll but was not handled in user code
其他信息:包含"路径表达式必须引用在类型上定义的导航属性.使用虚线路径作为参考导航属性,使用选择"运算符作为集合导航属性.
Additional information: The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
请注意,我曾尝试使用JOIN
s进行此操作,但这很丑陋,因此我决定使用内置的nav属性.
Note that I had tried doing this using JOIN
s but that was ugly, so I decided to use the built-in nav properties.
我做错了什么?谢谢.
推荐答案
您不能在Include
语句上使用Where
,在Include
之后应用任何过滤器.
You can't use Where
on Include
statements, apply any the filter after the Include
.
您可以在上下文构造函数中禁用延迟加载:
You can disable Lazy Loading in the Context constructor:
class EfContext : DbContext
{
public EfContext()
{
Configuration.LazyLoadingEnabled = false;
}
...
然后,如果您已经在ServiceStatu
模型中定义了ServiceId
属性:
Then, if you have defined a ServiceId
property in ServiceStatu
Model:
Service service = ...;
context.ServiceStatus.Where(s => ServiceId == service.Id).Load()
或
context.Entry(service).Collection(s => s.ServiceStatu).Load()
但是一旦加载另一个属于该service
的ServiceStatu
, EF 会将其添加到service
的集合中.
But as soon you load another ServiceStatu
belonging to that service
, EF will add it to the collection of the service
.
在您的情况下,您可以使用惰性加载并投影结果或过滤状态并将其存储在另一个变量中:
In your case you can use Lazy Load and project the results or filter the status and store it in another variable:
var newQuery = query.Select(s => new { Service = s, FilteredStatus = s.ServiceStatu.Where(ss => ss.ServiceStatusID == 7) });
//or
var status = service.ServiceStatu.Where(s => s.ServiceStatusID == 7);
这篇关于LINQ中导航属性查询的ArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!