【问题标题】:System.Linq.Dynamic - No property or field exists in type ICollectionSystem.Linq.Dynamic - ICollection 类型中不存在任何属性或字段
【发布时间】: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


【解决方案1】:

我之前遇到过这种情况,我的结论是:在 Lambda 扩展方法中,您只能加载第一级相关对象。 您可以获取 customerInterests 列表,但您无法获取此列表的外国记录。 但您可以改用 LINQ 查询。

var query=from c in DbContext.Customers
from ci in c.CustomerInterests
from co in ci.Courses 
where /// your conditions 
select new {
id=c.id,
name=c.name,
customerInterests= new {
customerId= ci.customerId,
courseId=ci.courseId ,
courses= new {
Name=co.Name
/// Other Courses attributes
}
}
}

已编辑 如果您使用的是 EF7 ,则可以使用 ThenInclude 方法加载第二级外国记录

db.Customers.Include( customer => customer.Orders). ThenInclude( order=> order.OrderDetails);

【讨论】:

    猜你喜欢
    • 2016-07-28
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多