将sql Query转换为LINQ返回始终为null

时间:2018-02-22 16:38:16

标签: c# sql linq

我有这个SQL查询:

SELECT *
  FROM [Incentivos].[dbo].[Incentivos] AS I 
  INNER JOIN [Incentivos].[dbo].[Captura] AS C ON I.CapturaID = C.ID
  WHERE I.EmpleadoID =4530 and C.mdEstatusRegistro = 1

它工作正常,现在我想用它与LINQ,所以我尝试

  var ce = _contexto.Empleados.Where(x => x.nCodigoEmpleado == codigoEmpleado)
           .Select(x => x.ID).FirstOrDefault(); //4530 value

 var captura = _contexto.Capturas.Where(x => x.mdEstatusRegistro).ToList(); //Captura table

  //JOIN
  var Incentivo = _contexto.Incentivos 
  .Join(captura, x => x.CapturaID, y => y.ID, (x, y) => new { x, y })
  .Where(x => x.y.mdEstatusRegistro && x.x.EmpleadoID == ce)
  .Select(b=> b.x).FirstOrDefault();

问题是加入永远是空的,我做错了什么?问候

更新 我更改查询更简单,如

 var Incentivo = from incentivos in _contexto.Incentivos
                 join captura in _contexto.Capturas on incentivos.CapturaID equals captura.ID
                 where (incentivos.EmpleadoID == ce) && (captura.mdEstatusRegistro == true)
                 select incentivos;

但现在在查询后我想访问Incentivo,如:

Incentivo.nPorcentajeAJU //Property of Incentivo table

但我不能,我现在如何访问变量?

1 个答案:

答案 0 :(得分:1)

您的LINQ查询将始终返回List<Incentivos>,因此您访问Incentivo.nPorcentajeAJU的唯一方法是foreach循环。但是,当您查询状态只返回一条记录时,您必须这样写:

var Incentivo = (
  from incentivos in _contexto.Incentivos
  join captura in _contexto.Capturas on incentivos.CapturaID equals captura.ID
  where (incentivos.EmpleadoID == ce) && (captura.mdEstatusRegistro == true)
  select incentivos
).First<Incentivos>();

int someVar = Incentivo.Some_Property; //Access the property like so