选择包含Linq中其他对象列表的新对象

时间:2018-09-10 13:22:33

标签: c# linq

我有一个包含其他对象列表的对象。

public class MyNewClassWithEverything
{
    public MasterItem itemMaster { get; set; }
    public Item item { get; set; }
    public List<Itemfields> Itemsfields { get; set; }
    public List<ItemMasterfields> ItemMasterfields { get; set; }
}

在我的Linq中,我有

var mainData = from uo in _context.UserOrgs
   join m in _context.MasterItem on uo.Organization equals m.Organization
   join i in _context.Item on m.Id equals i.MasterId
   join p in _context.ItemMasterfields on i.MasterId equals p.MasterId
   join z in _context.Itemfields on i.Id equals z.ItemId
   where uo.UserId == 6923 && m.DatePaid >= PaymentStartDate && m.DatePaid < PaymentEndDate
   select new MyNewClassWithEverything
   {
       Itemsfields = new List<Itemsfields> { z },
       ItemMasterfields = new List<ItemMasterfields> { p },
       ItemMaster = m,
       Items = i
   };

但是,当我运行我的应用程序时,我遇到了异常

  

给定表达式'new MyNewClassWithEverything()    在嵌套中不包含搜索到的表达式“ [z]”    具有成员分配或MemberBindingExpression的NewExpression

我应该如何填充新列表?

2 个答案:

答案 0 :(得分:1)

您可以在联接中添加into子句以将联接的记录用作组:

var mainData = from uo in _context.UserOrgs
   join m in _context.MasterItem on uo.Organization equals m.Organization
   join i in _context.Item on m.Id equals i.MasterId
   join p in _context.ItemMasterfields on i.MasterId equals p.MasterId
      into ps
   join z in _context.Itemfields on i.Id equals z.ItemId
      into zs
   where uo.UserId == 6923 && m.DatePaid >= PaymentStartDate && m.DatePaid < PaymentEndDate
   select new MyNewClassWithEverything
   {
       Itemsfields = zs.ToList(),
       ItemMasterfields = ps.ToList(),
       ItemMaster = m,
       Items = i
   };

如果您在ToList上遇到错误,则可以将属性类型更改为IEnumerable<T>或致电AsEnuerable()并进行第二次投影以将组转换为EF之外的列表查询。

答案 1 :(得分:0)

您可以尝试使用_context.Itemfields.Where而不是linq join来获取属性中的集合。

var mainData = from uo in _context.UserOrgs
               join m in _context.MasterItem on uo.Organization equals m.Organization
               join i in _context.Item on m.Id equals i.MasterId
               where uo.UserId == 6923 && m.DatePaid >= PaymentStartDate && m.DatePaid < PaymentEndDate
               select new MyNewClassWithEverything
               {
                   Itemsfields = _context.Itemfields.Where(x=>x.ItemId == i.Id).toList(),
                   ItemMasterfields = _context.ItemMasterfields.Where(l=>l.MasterId == i.MasterId).toList(),
                   ItemMaster = m,
                   Items = i
               };