LINQ将模型ICollection传递给另一个模型中具有Name和Surname的字符串

时间:2017-03-29 13:33:26

标签: c# linq linq-to-entities

我有一个字段,它是模型ICollection“Parties”的集合,它在另一个模型“Matter”中。我想提取每一方的名称和姓氏,并使用LINQ分隔“/”。我将这些放入名为Investors的领域,这是第二个项目。

这是我的疑问:

    var matterQuery = (from matter in context.Matters
  select new
  {
      matter.ID,
      matter.AttorneyRef,
      matter.Status,
      matter.ProductType,
      matter.IsDiscarded,
      matter.Base_CreatedDate,
      matter.Base_CreatedBy,
      matter.BranchID,
      matter.InstitutionID,
      matter.InvestmentTypeID,

      StatusName = matter.MatterStatu != null ? matter.MatterStatu.Name : string.Empty,
      ProductTypeName = matter.ProductType1 != null ? matter.ProductType1.Name : string.Empty,
      AccountNumber = matter.Account != null ? matter.Account.AccountNumber : string.Empty,
      CreatedBy = matter.Paralegal != null ? matter.Paralegal 
      : matter.AspNetUser != null ? matter.AspNetUser.FirstName + " " + matter.AspNetUser.LastName
      : matter.User != null ? matter.User.Firstname + " " + matter.User.Surname
      : string.Empty,
      IntermediaryName = matter.IntermediaryBranch != null ? matter.IntermediaryBranch.Intermediary.Name 
      : matter.Attorney != null ? matter.Attorney.AttorneyName
      : string.Empty,
      CloseRequested = matter.CloseAccounts.Where(x => x.Status == (int)CloseAccountStatusEnum.Authorised).Count() > 0,
      StatementRequested = matter.Account != null ? matter.Account.StatementRequested : false,
      RequestedDate = matter.RequestedDate.HasValue ? matter.RequestedDate.Value : matter.Base_CreatedDate,
      Investors = matter.Parties.Select(x => x.Name.ToString()).Concat(matter.Parties.Select(x => x.Surname.ToString())),
      SoftLock = matter.SoftLock,
  })
   .AsQueryable();

我在1长字符串中需要这个,因为我正在搜索过滤器的结果以及以下行:

(x.Investors != null && x.Investors.ToLower().Contains(search))

要求它采用字符串格式。我想将结果显示为“Name1 Surname1 / Name2 Surname2 / ...”

我该怎么做?

编辑:

我尝试过Join和Aggregate但是我收到了错误:

base {System.SystemException} = {System.NotSupportedException:LINQ to Entities无法识别方法'System.String Join(System.String,System.Collections.Generic.IEnumerable`1 [System.String])'方法,并且此方法无法转换为商店表达式。    在System.Da ......

和...

System.NotSupportedException:LINQ to Entities无法识别方法'System.String Aggregate [String](System.Collections.Generic.IEnumerable 1[System.String], System.Func 3 [System.String,System.String,System.String] )'

3 个答案:

答案 0 :(得分:1)

假设您的搜索工作正常并且搜索结果为frame=cvQueryFrame(capture); if (frame.empty()) break;,您可以执行此操作以创建所需的字符串:

IEnumerable<string>

答案 1 :(得分:0)

如果我确实理解你的问题,你有两个选择:

  1. 从数据库中获取所有结果并进行本地连接
  2. 调用sp来执行此操作
  3. 选中此Is there a "for xml path" equivalent in LINQ to SQL?

答案 2 :(得分:0)

我通过以下方式解决了这个问题:

在原始查询中:

select new{
Investors = matter.Parties.Select(x => x.Name + " " + x.Surname), 
}

在搜索中:

matterQuery.Where(x =>
(x.Investors.Any(y => y.ToLower().Contains(searchString)))
);

将数据传输到ViewModel时:

Investors = String.Join(" / ", matter.InvestorNames),