2011-08-10 36 views
1

如何按照「Linq To Entities中只允許無參數的構造函數和初始化程序」的方式給出錯誤信息。我正在嘗試從我的實體生成HTML以使用AJAX更新HTML表格。使用linq-to-entities生成xml的錯誤

public class Foo 
{ 
    public int Bar1 { get; set; } 
    public string Bar2 { get; set; } 
    public DateTime Bar3 { get; set; } 
} 

XElement[] elements = (
      from x in FooEntities.Foos 
      select new XElement("tr", 
       new XElement("td", HttpUtility.HtmlEncode(x.Bar1)), 
       new XElement("td", HttpUtility.HtmlEncode(x.Bar2)), 
       new XElement("td", HttpUtility.HtmlEncode(x.Bar3))) 
      ) 
      .ToArray<XElement>(); // Error 

XElement html = new XElement("table", headerXElement, elements); 
+1

請注意,您不需要在'ToArray'調用中指定類型參數,因爲它將由編譯器推斷出來。 –

回答

1

那麼,錯誤信息本身就說明了一切。

Linq To Entities只允許無參數的構造函數和初始值設定項。

LINQ to Entities可能很難取悅,您怎麼看?
呼叫ToArray之後你得到的實體所以你只能用LINQ處理到對象:

var foos = (from x in FooEntities.Foos 
      select x).ToArray(); 

XElement[] elements = (
      from x in foos 
      select new XElement("tr", 
       new XElement("td", HttpUtility.HtmlEncode(x.Bar1)), 
       new XElement("td", HttpUtility.HtmlEncode(x.Bar2)), 
       new XElement("td", HttpUtility.HtmlEncode(x.Bar3))) 
      ) 
     .ToArray(); 

XElement html = new XElement("table", headerXElement, elements); 

這也是分開的數據庫調用(第一查詢)和業務對象/ XML生成(在一個很好的做法第二個查詢),因爲您立即看到針對數據庫執行的操作以及內存中的操作

+0

我同意,哈哈。我想到了你發佈這個的時候。我做了foreach(var x中的foos)html.Add(new XElement ... –