【问题标题】:How do I call a method from within a linq query that is retrieving from an Entity Framework model如何从从实体框架模型检索的 linq 查询中调用方法
【发布时间】:2013-04-10 13:37:18
【问题描述】:

我有以下代码

return (_entities.Users.Select(profile => new ProfileUserListItemDto
                {
                    Email = profile.Email,
                    FirstName = profile.FirstName,
                    Id = profile.Id,
                    LastName = profile.LastName,
                    Role = DtoEntityLookups.EntityRoleToDtoRole(profile.Role),
                    TimeZone = profile.TimeZone
                })).ToList();

public static RoleTypeEnum EntityRoleToDtoRole(Role role)
        {
            if (role == null)
                throw new NoNullAllowedException("Null role supplied to EntityRoleToDtoRole method");

            if (role.Id.ToString() == RolesGuid.AdministratorGuid)
                return RoleTypeEnum.Administrator;
            if (role.Id.ToString() == RolesGuid.ClientGuid)
                return RoleTypeEnum.Client;

            throw new InvalidDataException("Unknown role supplied");
        }

调用时出现以下错误

LINQ to Entities 无法识别方法 RoleTypeEnum EntityRoleToDtoRole(User.Entities.Entities.Role)' 方法,并且此方法无法转换为存储表达式。

如何将EntityRoleToDtoRole 转换为可从实体框架查询中调用?

【问题讨论】:

    标签: c# linq entity-framework linq-to-entities expression-trees


    【解决方案1】:

    您需要使用 Users.AsEnumerable() 才能在 linq 中调用方法。

    return (_entities.Users.AsEnumerable().Select(profile => new ProfileUserListItemDto
                    {
                        Email = profile.Email,
                        FirstName = profile.FirstName,
                        Id = profile.Id,
                        LastName = profile.LastName,
                        Role = DtoEntityLookups.EntityRoleToDtoRole(profile.Role),
                        TimeZone = profile.TimeZone
                    })).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      相关资源
      最近更新 更多