LINQ C# - API CONTROLLER - 评估查询
LINQ C# - API CONTROLLER - Evaluate query
我有一个 table 叫做“Cowork”,另一个叫做“Commune”。在控制器中,我收到一个名为 NameCommune 的参数,鉴于该值,我需要找到与接收到的参数匹配的 ID,上面的结果我需要评估该 ID 是否存在于“COWORK”table 中。 (两个表是相关的)我是使用 LINQ 的新手,对此有什么想法吗?我尝试了以下方法,但它 returns 是一个空的 [ ]
public IActionResult GetNearbyPlaces(string nameComuna)
{
IQueryable<Commune> queryCommune = _context.Commune;
IQueryable<Cowork> queryCowork = _context.Cowork;
var codeCommune = (from code in queryCommune where code.name == nameComuna select code.code);
var coworkList = (from c in _context.Cowork where c.commune_code == codeCommune.ToString() select c).ToList();
return Ok(coworkList); // This returns an empty [ ]
}
在我的常用table中,ID或我的主键由名称代码表示。
你可能想要这样的东西:
public IActionResult GetNearbyPlaces(string nameComuna)
{
IQueryable<Commune> queryCommune = _context.Commune;
IQueryable<Cowork> queryCowork = _context.Cowork;
var query =
from code in queryCommune
where code.name == nameComuna
join c in _context.Cowork on code.code equals c.commune_code
select c;
return Ok(query.ToList());
}
或者可能:
public IActionResult GetNearbyPlaces(string nameComuna)
{
IQueryable<Commune> queryCommune = _context.Commune;
IQueryable<Cowork> queryCowork = _context.Cowork;
var query =
from c in _context.Cowork
join code in queryCommune.Where(x => x.name == nameComuna)
on c.commune_code equals code.code into codes
where codes.Any()
select c;
return Ok(query.ToList());
}
我有一个 table 叫做“Cowork”,另一个叫做“Commune”。在控制器中,我收到一个名为 NameCommune 的参数,鉴于该值,我需要找到与接收到的参数匹配的 ID,上面的结果我需要评估该 ID 是否存在于“COWORK”table 中。 (两个表是相关的)我是使用 LINQ 的新手,对此有什么想法吗?我尝试了以下方法,但它 returns 是一个空的 [ ]
public IActionResult GetNearbyPlaces(string nameComuna)
{
IQueryable<Commune> queryCommune = _context.Commune;
IQueryable<Cowork> queryCowork = _context.Cowork;
var codeCommune = (from code in queryCommune where code.name == nameComuna select code.code);
var coworkList = (from c in _context.Cowork where c.commune_code == codeCommune.ToString() select c).ToList();
return Ok(coworkList); // This returns an empty [ ]
}
在我的常用table中,ID或我的主键由名称代码表示。
你可能想要这样的东西:
public IActionResult GetNearbyPlaces(string nameComuna)
{
IQueryable<Commune> queryCommune = _context.Commune;
IQueryable<Cowork> queryCowork = _context.Cowork;
var query =
from code in queryCommune
where code.name == nameComuna
join c in _context.Cowork on code.code equals c.commune_code
select c;
return Ok(query.ToList());
}
或者可能:
public IActionResult GetNearbyPlaces(string nameComuna)
{
IQueryable<Commune> queryCommune = _context.Commune;
IQueryable<Cowork> queryCowork = _context.Cowork;
var query =
from c in _context.Cowork
join code in queryCommune.Where(x => x.name == nameComuna)
on c.commune_code equals code.code into codes
where codes.Any()
select c;
return Ok(query.ToList());
}