Entity Framework 获取特定列的 Lambda 表达式

Entity Framework Lambda Expression To Get Specific Columns

我有以下查询,但它抛出错误:

Cannot implicitly convert system.collections.generics.lists <> to system.collections.generics.ienumerable

查询:

public IEnumerable<ApplicationUser> GetUsersByRole(string roleName)
{
    var role = _context.Roles.FirstOrDefault(r => r.Name == roleName);

    return _context.Users
             .Where(u => u.Roles.Any(r => r.RoleId == role.Id))
             .Select(u => new ApplicationUser { Id = u.Id, FullName = u.FullName })
             .ToList();
}

在我的应用程序用户 class 中,我有 Fullname 属性 定义如下:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string FullName
    {
        get {  return string.Format("{0} {1}", FirstName, LastName); }
    }
}

我也遇到错误

property Indexer ApplicationUser.Fullname cannot be assigned to -- it is read only

有什么方法可以让全名 属性 保持只读状态而不添加 setter?

您正在投射到匿名类型。你将不得不使用

.Select(u => new ApplicationUser { Id = u.Id, Name = u.UserName}).ToList();

给return一个IEnumerable<ApplicationUser>