【发布时间】:2016-07-10 19:54:02
【问题描述】:
我将 System.Linq.Dynamic 与 EntityFramework 一起使用。我的实体如下:
public class Customer
{
public Customer()
{
CustomerInterests = new List<CustomerInterest>();
}
public int Id { get; set; }
public string Name { get; set; }
public ICollection<CustomerInterest> CustomerInterests { get; set; }
}
public class CustomerInterest
{
public int Id { get; set; }
public int CustomerId { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
}
下面是我的方法:
public dynamic Get(long customerId)
{
var query = DbContext.Customers.Include("CustomerInterests").Include("CustomerInterests.Course").AsQueryable();
return query.Where(filter => filter.Id == customerId).Select("new(id,name,customerInterests)");
}
JSON 结果:
{
"id": 2003,
"name": "name customer",
"customerInterests": [
{
"customerId": 2003,
"courseId": 2,
"course": null,
"id": 2016
},
{
"customerId": 2003,
"courseId": 3,
"course": null,
"id": 2017
}
]
}
我正在尝试加载属性 Course,但它总是返回 null,正如您在 JSON 结果中看到的那样。
如何创建选择器new(....) 以正确加载属性Course。我已经尝试过new (customerInterests.course) as customerInterests.course,但没有成功。
不要忘记我正在尝试导航Customer(对象)-> CustomerInterests(集合)-> 为每个项目加载Course(对象)。
如果你能在这件事上帮助我,我将不胜感激。
【问题讨论】:
-
您将查询投影到匿名类型。 Include never works 如果你预测结果。
-
@GertArnold 我同意你的看法。我只是添加了 Include 以使问题更容易,但实际上重点是如何正确编写选择器 new (...)。 =)
-
我认为动态 LINQ 不可能做到这一点。
标签: c# json entity-framework linq