【问题标题】:Error using linq-to-entities to generate xml使用 linq-to-entities 生成 xml 时出错
【发布时间】:2011-08-10 20:31:11
【问题描述】:

以下内容如何给我一个错误,类似于“Linq To Entities 中只允许使用无参数构造函数和初始化程序”。我正在尝试从我的实体生成 HTML 以使用 AJAX 更新 HTML 表。

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);

【问题讨论】:

  • 附带说明,您不需要在ToArray 调用中指定类型参数,因为它将由编译器推断。

标签: ajax linq linq-to-entities linq-to-xml


【解决方案1】:

嗯,错误信息不言自明。

Linq To Entities 中只允许使用无参数的构造函数和初始化器。

LINQ to Entities 很难取悦,你怎么看?
在获得实体后立即调用 ToArray,这样您就只处理 LINQ to Objects:

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 生成(第二个查询)分开也是一种很好的做法,因为您会立即看到对数据库执行的内容以及内存中的内容

【讨论】:

  • 我同意,哈哈。我在你发这个的时候就知道了。我做了 foreach (var x in foos) html.Add(new XElement...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
相关资源
最近更新 更多