0

I am trying to use the Entity Framework in my ASP MVC 3 site to bind a Linq query to a GridView datasource. However since I need to pull information from a secondary table for two of the fields I am getting the error

LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable'1[System.String])' method, and this method cannot be translated into a store expression.

I would like to be able to do this without creating a dedicated view model. Is there an alternative to using String.Join inside a Linq query?

var grid = new System.Web.UI.WebControls.GridView();

//join a in db.BankListAgentId on b.ID equals a.BankID
var banks = from b in db.BankListMaster
    where b.Status.Equals("A")
    select new
    {
        BankName = b.BankName,
        EPURL = b.EPURL.Trim(),
        AssociatedTPMBD = b.AssociatedTPMBD,
        FixedStats = String.Join("|", from a in db.BankListAgentId
                                      where a.BankID == b.ID &&
                                      a.FixedOrVariable.Equals("F")
                                      select a.AgentId.ToString()),
        VariableStats = String.Join("|", from a in db.BankListAgentId
                                         where a.BankID == b.ID &&
                                         a.FixedOrVariable.Equals("V")
                                         select a.AgentId.ToString()),
        SpecialNotes = b.SpecialNotes,
    };

grid.DataSource = banks.ToList();
grid.DataBind();
4

1 回答 1

1

如果你不太担心性能(因为它有子查询,它可能会对数据库产生 n+1 个查询,如果数据库行很大,你可能会获取不必要的数据),最简单的解决方法是添加一个AsEnumerable()在 Web/应用程序端执行 String.Join;

var banks = (from b in db.BankListMaster 
             where b.Status.Equals("A") select b)
            .AsEnumerable() 
            .Select(x => new {...})

在调用 时AsEnumerable(),Linq 查询的其余部分将在应用程序端而不是数据库端完成,因此您可以自由使用完成工作所需的任何运算符。当然,在此之前,您需要尽可能多地过滤结果。

于 2013-05-02T16:54:33.153 回答