Linq to Entities inside XML Literal Produces "Only Parameterless Constructors are Supported in Linq to Entities"

Linq to Entities inside XML Literal Produces "Only Parameterless Constructors are Supported in Linq to Entities"

我正在尝试为我的 ASP.NET MVC 网络应用程序创建动态 XML 站点地图。这些页面是根据 entity framework 6 模型从数据库中检索到的数据进行结构化和可预测的。我想简单地使用 XML 文字从数据库中检索每个项目,有点像 here.

发生的事情

我的声明如下所示:

Dim xmlSitemap = <?xml version="1.0" encoding="UTF-8"?>
                 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                     <url>
                         <loc>https://example.com</loc>
                     </url>
                     <url>
                         <loc>https://example.com/Home/Contact</loc>
                     </url>
                     <%= From blog in db.Blogs Select <url>
                                                          <loc>https://example.com/BlogPosts/<%= blog.PostId %></loc>
                                                      </url> %>
                </urlset>

运行 此代码导致 System.NotSupportedException: 'Only parameterless constructors and initializers are supported in LINQ to Entities.'

修改模型以包含不带参数的 Public Sub New() 并不能解决此错误。根据我在尝试之后的研究,我猜测这与我在 Linq 查询中连接字符串这一事实有关,但我不知道另一种方式。有没有办法以这种方式创建站点地图,还是我要求太多了?

我猜测在 .NET 级别,由该标记生成的编译表达式太复杂而无法在 Entity Framework 中处理(即在 SQL 语句中)。尝试在 db.Blogs 之后添加 .ToList().AsEnumerable() 以强制将 LINQ 语句的其余部分放入 LINQ-to-Objects 上下文中。

注意:您需要确保了解这是在做什么,并避免在 Where 子句之前执行 .ToList(),例如,以避免严重的性能损失。