Linq to sql with union



>我有两个类似的查询,需要对它们应用联合。第一个查询的一部分如下所示:

var query1 = from contract in ContractRepo.GetAll()
(lots of joins)
select new ContractViewModel(){
(lots of fields)     
Attachments = null
}

第二个查询的一部分:

var query2 = from com in CommRepo.GetAll()
join comAtt in AttachmentRepo.GetAll() on   
com.Id equals comAtt.comId into att
select new ContractViewModel(){
(lots of fields),
Attachment = from a in att
    select new AttachmentViewModel()
    {
    (some fields)
    }
}
var query = query1.Union(query2);

问题出在类型为 IEnumerable 的附件字段上。我无法分配 null 或初始化空列表,因为我收到异常。我无法从第一个查询中删除此字段,因为联合不起作用。

有什么建议吗?

使用默认值初始化属性,不要设置 null:

class ContractViewModel
{
    public IEnumerable<AttachmentViewModel> Attachments {get; set;} = Enumerable.Empty<AttachmentViewModel>();
}

最新更新