0

我正在使用 EF 查找联系人,然后在图表中包含一家公司,然后将其放入 DTO。我只希望创建公司 DTO(如果存在),如果不存在,我不想包含空白 DTO。(它在 REST 服务中传输,我不想要无数的空标签。)

return (from c in _dc.Contact.Include("Company")
                where c.ContactId == id
                select new ContactDto
                {
                    ContactId = c.ContactId,
                    FirstName = c.FirstName,
                    LastName = c.LastName,
                    Company = new CompanyDto
                                {
                                    CompanyId = c.Company.CompanyId,
                                    Name = c.Company.Name
                                } 
                }).ToList();

对于没有公司关联的联系人,这会崩溃。通常我会创建一个空白对象,但是如上所述,这将包括很多空白标签。

我想做类似的事情(这显然是不可能的)

return (from c in _dc.Contact.Include("Company")
                where c.ContactId == id
                select new ContactDto
                {
                    ContactId = c.ContactId,
                    FirstName = c.FirstName,
                    LastName = c.LastName,
                    if (c.Company !=null) 
                    {
                        Company = new CompanyDto
                                {
                                    CompanyId = c.Company.CompanyId,
                                    Name = c.Company.Name
                                } ;
                    }
                }).FirstOrDefault();

先感谢您

奥利

4

2 回答 2

0

尝试这样的事情。我面前没有 VS,所以你需要注意语法。

return (from c in _dc.Contact 
              join co in _dc.Company on c.CompanyId equals co.CompanyId into subCompanies
                from sc in subCompanies.DefaultIfEmpty()
                where c.ContactId == id
                select new ContactDto
                {
                    ContactId = c.ContactId,
                    FirstName = c.FirstName,
                    LastName = c.LastName,
                    Company = sc
                }).FirstOrDefault()
于 2013-08-03T08:36:44.000 回答
0

也许您可以尝试使用三元运算符:

            Company = (c.Company!=null)?
                (new CompanyDto
                {
                    CompanyId = c.Company.CompanyId,
                    Name = c.Company.Name
                })
                :null
于 2013-07-31T02:25:27.533 回答