【问题标题】:Cannot implicitely convert type WebApplication1.models.Table1 to int无法将类型 WebApplication1.models.Table 1 隐式转换为 int
【发布时间】:2021-11-16 12:59:21
【问题描述】:

我想在 get api 中使用 sql 查询:

[Route("empLevel/{id}")]
public IActionResult GetEmpHierarchy(int id)
{
    List<Employee> emp = entity.Employees.ToList();
    List<Employee> mngr = entity.Employees.ToList();

    var query = (from e in emp
                 join m in mngr on e.MngId equals m.Id into tab1
                 from mngrN in tab1.DefaultIfEmpty()
                 select new Employee { Id = e, MngId = m}).ToList();
    return Ok(query);
}

但我在ID = e 行收到一个错误,它说e 不能转换为int。

在我的模型课中,我有:

public partial class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Grade { get; set; }
    public int? MngId { get; set; }
    public virtual SalarySplit GradeNavigation { get; set; }        
}

请给出解决方案。

【问题讨论】:

    标签: c# entity-framework asp.net-core asp.net-web-api get


    【解决方案1】:

    变量e 表示Employee 类型的对象。您正在尝试将整个对象分配给属性Id。相反,您应该使用该 e 对象的属性中的值。

    var query = (from e in emp
                 join m in mngr on e.MngId equals m.Id into tab1
                 from mngrN in tab1.DefaultIfEmpty()
                 select new Employee { Id = e.Id, MngId = m.Id}).ToList();
    

    奖励:如果我没记错的话,过滤不会在那里应用,你会得到有或没有经理的对象(两者)。在这种情况下,可以简化查询:

    var query = (from e in emp
                 select new Employee { Id = e.Id, MngId = e.MngId}).ToList();
    

    【讨论】:

      【解决方案2】:

      因为 e 是一种对象,而您的 ID 是 int。 所以你可能想要这样的东西。

      select new Employee { Id = e.MngId, MngId =  m.Id}).ToList();
      

      【讨论】:

        猜你喜欢
        • 2016-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-18
        相关资源
        最近更新 更多