【问题标题】:Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[ClaimBuildMVC.Models.UserDetail]' to type 'System.Co无法将“System.Data.Entity.Infrastructure.DbQuery`1[ClaimBuildMVC.Models.UserDetail]”类型的对象转换为“System.Co”类型
【发布时间】:2016-03-22 16:02:05
【问题描述】:

我是使用 LINQ 的实体框架的 MVC 新手,我收到以下错误

无法将类型为“System.Data.Entity.Infrastructure.DbQuery 1[BuildMVC.Models.UserDetail]”的对象转换为类型“System.Collections.Generic.IList`1[System.Object]”

下面是代码

public interface IGenericRepository<TEntity> where TEntity : class
{       
    IList<dynamic> GetRecord(long Id);      
    void Add(TEntity entity);
    void update(TEntity entity);
}

public IList<dynamic> GetRecord(long Id)
{
    var _lstUser=(IList<dynamic>)(from ud in _dbContext.UserDetails
                                  join rs in _dbContext.RolesMasters
                                  on ud.FkRoleId equals rs.ID
                                  select new UserDetail
                                  {
                                      FirstName = ud.FirstName + " " + ud.LastName,
                                      PostalStreet=rs.RoleName, 
                                      IsDeleted=ud.IsDeleted
                                  });
    return _lstUser;
}

我正在从第二个表中获取rs.RoleName 列,但是由于我使用了UserDetail 类,所以我从UserDetail 中获取了PostalStreet 列,不知道这是否正确。

【问题讨论】:

  • 你为什么要把它转换成dynamic?删除(IList&lt;dynamic&gt;)
  • public IList GetRecord(long Id) { var _lstUser=(IList)(from ud in _dbContext.UserDetails join rs in _dbContext.RolesMasters on ud.FkRoleId 等于 rs.ID select新用户详细信息 {FirstName=ud.FirstName+" "+ud.LastName,PostalStreet=rs.RoleName,IsDeleted=ud.IsDeleted} ) ;返回_lst用户; }
  • 编辑您的问题并删除不可读的评论。再说一次,强制转换为动态的原因是什么(并使其在您的视图中不可用。但如果您真的想这样做,请在查询中添加 .ToList()
  • 我正在使用通用存储库模式,我已经定义了类似这样的 IList GetRecord(long Id);我正在实施已在 cmets 中显示的内容。要编辑什么,请您详细说明而不是否决
  • 点击问题下方的“编辑”链接并编辑您的代码。

标签: asp.net-mvc entity-framework linq


【解决方案1】:
 public static IEnumerable<CustomerOrder> GetCustomerOrder(this IRepository<Customer> repository, string country)
    {
        var customers = repository.GetRepository<Customer>().Queryable();
        var orders = repository.GetRepository<Order>().Queryable();
        var query = from c in customers
            join o in orders on new {a = c.CustomerID, b = c.Country}
                equals new {a = o.CustomerID, b = country}
            select new CustomerOrder
            {
                CustomerId = c.CustomerID,
                ContactName = c.ContactName,
                OrderId = o.OrderID,
                OrderDate = o.OrderDate
            };

        return query.AsEnumerable();
    }

在这里,我创建了额外的类,其中包含 WebGrid 中使用的两个类的变量。

【讨论】:

    猜你喜欢
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多