0

我有以下两行代码,它们首先从查询中返回一个项目,然后使用第一个查询的值创建另一个项目。我想将这两行合并为一个声明。请记住,在某些情况下,第一个查询的结果可能为空。

var x = uow.Profiles.FindByID(profileId).Competitor;

return Json(new Organisation() { Name = x.Name, ID = x.ID, IsClient = x.IsClient, IsDeleted = x.IsDeleted }, JsonRequestBehavior.AllowGet);
4

2 回答 2

0

如果这是您关心的问题,也许您可​​以添加一个空检查:

var result = uow.Profiles.FindByID(profileId);

if(result != null)
{
   var competitor = result.Competitor;
   return Json(new Organisation() { Name = competitor.Name, ID = competitor.ID, IsClient = competitor.IsClient, IsDeleted = competitor.IsDeleted }, JsonRequestBehavior.AllowGet);
}

return null; // or whatever you can default to

不确定到底是什么问题以及 LINQ 如何提供帮助(您不必使用它),只需确保您的代码可读即可。

于 2013-05-28T12:28:24.327 回答
-1

编辑:最后使用 IEnumerable (我假设 Profiles 是一个)

ouw.Profiles.Single(p => p.Id == profileId).Select
(p => Json(
    new Organisation()
    {
        Name = p.Competitor.Name,
        ID = p.Competitor.ID,
        IsClient = p.Competitor.IsClient,
        IsDeleted = p.Competitor.IsDeleted
    },
    JsonRequestBehavior.AllowGet)
);
于 2013-05-28T12:27:39.157 回答