0

我想在我的ASP MVC 3站点中使用实体框架将Linq查询绑定到GridView数据源。然而,因为我需要从一个辅助表中提取信息两个领域的,我得到的错误替代在Linq查询中使用String.Join

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.

我希望能够做到这一点,而无需创建一个专用的视图模型。 Linq查询中是否有使用String.Join的替代方法?

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(); 
+0

不知道你的模式/访问模式等,如果你改变查询var banks =(从db.BankListMaster 其中b.Status.Equals(“A”)选择b).AsEnumerable ().Select(x => new {...})'而不是?否则,您应该能够将FixedStats/VariableStats设置为字符串集合,并执行第二次select(在AsEnumerable()'之后)来加入字符串。 – 2013-05-02 16:08:59

+0

性能不是问题,这是一个相对较小的应用程序。我对这种语言很陌生,你能说明一下吗?我将注释中的语法复制到'new {...}'行,然后将我在'{...}'部分中的'select new'部分中的所有内容放在我的帖子中。在将'b.'替换为'x.'后,程序抛出了一个'NullReferenceException' – NealR 2013-05-02 16:16:37

+0

这是在错误页面中单独出现的代码行:'.Select(x => new' – NealR 2013-05-02 16:23:31

回答

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查询的其余部分将在应用端,而不是数据库端进行,所以你可以自由地使用任何运营商,你需要得到这份工作完成。当然,在此之前,你会想尽可能地过滤结果。