System.NotSupportedException: LINQ to Entities 不支持指定的类型成员 'UserPrincipalName'

System.NotSupportedException: The specified type member 'UserPrincipalName' is not supported in LINQ to Entities

这个查询有什么问题:

var user = context.Users.Single(u => u.UserPrincipalName == "test@company.l");

为什么我会得到这个异常?

UserPrincipleName 是一个用户 属性...

System.NotSupportedException: The specified type member 'UserPrincipalName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

当我这样做时,一切都很好:

var users = context.Users.ToList();
var user = users.Single(u => u.UserPrincipalName == "test@company.l");

为什么单一适用于 Linq to Objects 但不适用于 Linq to Entities?

UserPrincipalName 必须映射到数据库中的列。 EF 尝试将 lambda 表达式 u => u.UserPrincipalName == "test@company.l" 转换为 sql 脚本,如果 UserPrincipalName 属性 未映射到 table 列,将会报错。

如果这是 IdentityElement 的 属性,则定义如下:

    [ConfigurationProperty(ConfigurationStrings.UserPrincipalName)]
    public UserPrincipalNameElement UserPrincipalName
    {
        get { return (UserPrincipalNameElement)base[ConfigurationStrings.UserPrincipalName]; }
    }

http://referencesource.microsoft.com/#System.ServiceModel/System/ServiceModel/Configuration/IdentityElement.cs,d784c9ed0cd1b486

它 returns 是一个字符串,这就是为什么您可以将它与 linq to objects 一起使用,但 EF 无法将其转换为 SQL 因为它通过转换一些 属性 在基地 class.