简体   繁体   中英

How do I call a method from within a linq query that is retrieving from an Entity Framework model

I have the following code

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

when invoked I get the following error

LINQ to Entities does not recognize the method RoleTypeEnum EntityRoleToDtoRole(User.Entities.Entities.Role)' method, and this method cannot be translated into a store expression.

How do I convert the EntityRoleToDtoRole to be callable from an Entity Framework query?

You need to use Users.AsEnumerable() to be able and call methods within 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM