首页 > 解决方案 > 将列表加入字符串

问题描述

我需要将字符串列表加入到 linq select 中的字符串中。我试过了:

var myEnt = from p in ctx.Project
    select new ProjectRepository.Project
    {
        Id = p.ProjectId,
        Desc = p.ProjectDesc,
        UsersProject = String.Join("; ", (
                                from up in ctx.usersProject join u in ctx.users
                                on up.user equals u.id into uloj from uj in uloj.DefaultIfEmpty()
                                where (up.deleted ?? false) == false
                                && up.projectId == p.Id
                                && (uj.deleted ?? false) == false
                                select uj.name + " " + uj.surname).ToList())
});

gridProg.DataSource = myEnt.ToList();
gridProg.DataBind();

但我有这个错误:

不支持将数据直接绑定到存储查询(DbSet、DbQuery、DbSqlQuery、DbRawSqlQuery)。而是使用数据填充 DbSet,例如通过在 DbSet 上调用 Load,然后绑定到本地数据。对于 WPF 绑定到 DbSet.Local。对于 WinForms 绑定到 DbSet.Local.ToBindingList()。对于 ASP.NET WebForms,您可以绑定到对查询调用 ToList() 的结果或使用模型绑定,有关详细信息,请参阅http://go.microsoft.com/fwlink/?LinkId=389592

谢谢你。

更新

将 .Tolist() 添加到 DataSource 绑定后出现新错误。

LINQ to Entities 无法识别方法 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' 方法,并且此方法无法转换为存储表达式。

标签: c#linq

解决方案


I have not tested it, but it will work. Make 2 different Queries

var Projects = (from up in ctx.usersProject join u in ctx.users
    on up.user equals u.id into uloj from uj in uloj.DefaultIfEmpty()
    where (up.deleted ?? false) == false
        && up.projectId == p.Id
        && (uj.deleted ?? false) == false
        select new { 
            ProjectId = up.projectId, 
            ProjectsList = uj.name + " " + uj.surname
        }).ToList();

var myEnt = from p in ctx.Project.AsEnumerable()
    select new ProjectRepository.Project
    {
        Id = p.ProjectId,
        Desc = p.ProjectDesc,
        UsersProject = String.Join("; ", Projects.Where(e=> p.ProjectId == e.ProjectId).Select(e=> e.ProjectsList).ToList())
    }).ToList();

推荐阅读