【问题标题】:Entity Framework Lambda Expression To Get Specific Columns获取特定列的实体框架 Lambda 表达式
【发布时间】:2016-07-17 18:41:31
【问题描述】:

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

无法将 system.collections.generics.lists 隐式转换为 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();
}

在我的应用程序用户类中,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); }
    }
}

我也有错误

属性 Indexer ApplicationUser.Fullname 不能分配给 -- 它是只读的

有没有办法在不添加 setter 的情况下保持 fullname 属性只读?

【问题讨论】:

  • .Select(u =&gt; new ApplicationUser { ... }).ToList();

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


【解决方案1】:

您正在投射到匿名类型。你必须使用

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

返回IEnumerable&lt;ApplicationUser&gt;

【讨论】:

  • 我现在收到以下错误:property Indexer ApplicationUser.Fullname cannot be assigned to -- it is read only 看到我上面的编辑?
猜你喜欢
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多