实体框架5基于包括动态选择

时间:2013-07-31 02:05:39

标签: c# linq select entity

我正在使用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();

提前谢谢

奥利

2 个答案:

答案 0 :(得分:0)

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

            Company = (c.Company!=null)?
                (new CompanyDto
                {
                    CompanyId = c.Company.CompanyId,
                    Name = c.Company.Name
                })
                :null

答案 1 :(得分: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()