c# - 无法在 LINQ to Entities 中将字符串转换为 GUID

标签 c# asp.net-mvc entity-framework linq

以下代码在 LinqPad 中运行良好:

(from u in AspNetUsers
     let userOrders = (from uo in UserOrders where uo.UserId == new Guid(u.Id) select uo)
     select u)

但是,当我尝试从 MVC 应用程序执行完全相同的代码时,会出现以下错误:

var users = (from u in ctx.Users
             let userOrders = (from uo in ctx.UserOrders where uo.UserId == new Guid(u.Id) select uo)
             select u);

Only parameterless constructors and initializers are supported in LINQ to Entities.

我不记得以前在 Linq to Entities 中将字符串转换为 GUID 时遇到过任何问题。我是否缺少一些引用资料?

我已经包含了我能想到的所有引用资料:

using System.Linq;
using System.Data.Entity;

为什么它在 LinqPad 中有效,但在 MVC 中无效?

编辑:奇怪的是,这似乎有效:

let userOrders = (from uo in ctx.UserOrders where uo.UserId.ToString() == u.Id select uo)

最佳答案

最终,我决定采用更简单的方法来转换我的 GUID .ToString(),如下所示:

let userOrders = (from uo in ctx.UserOrders where uo.UserId.ToString() == u.Id select uo)

原因是,AspNetUsers 的默认实现将列定义为 varchar,而不是 uniqueidentifier,因此为了更改它,我可能必须执行类似 How to make EF-Core use a Guid instead of String for its ID/Primary key 的操作我目前对此不感兴趣!

关于c# - 无法在 LINQ to Entities 中将字符串转换为 GUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41942491/

相关文章:

c# - int32.Parse(String, IFormatProvider) 在 int32.Parse(String) 上的用例是什么?

c# - 防止重复的 List<T> 条目

c# - .NET 核心 MvcHtmlString(TextboxFor, LabelFor).ToString() 错误

c# - 提交具体模型对象

c# - 该类型不具有 EdmEntityTypeAttribute 属性,但包含在具有 EdmSchemaAttribute 属性的程序集中

c# - 如何复制文件,覆盖现有文件?

asp.net-mvc - ASP.MVC 防伪 token 和加密错误

c# - Entity Framework 我的 AddOrUpdate 函数在哪里?

entity-framework - 在 Octopus Deploy CI to Azure 期间运行 Entity Framework 迁移

c# - 内部接口(interface)实现