Evgeni Dimitrov
Evgeni Dimitrov

Reputation: 22496

EF6 Navigation Properties map empty collection instead of null

I use linq to entities to fetch one to many relation. One Client has many Accounts.

            var query = from c in db.Client
                        where c.MetaProps.Deleteflag == 0
                        && c.ContractNumber.Equals(clientNumber)
                        select new
                        {
                            Client = c,
                            Accounts = c.Accounts.Where(a => a.IsActive),  
                        };
            contract = query.FirstOrDefault().Client;

The problem is that when there are no accounts in the DB the Accounts list is null. Is there a way to init it as an empty list, like when .Include() is used?

Upvotes: 0

Views: 514

Answers (1)

48klocs
48klocs

Reputation: 6103

Sure, you can use a null coalescing operator.

var query = from c in db.Client
            where c.MetaProps.Deleteflag == 0
            && c.ContractNumber.Equals(clientNumber)
            select new
            {
                Client = c,
                Accounts = c.Accounts.Where(a => a.IsActive) ?? Enumerable.Empty<Account>()  
            };
contract = query.FirstOrDefault().Client;

Upvotes: 1

Related Questions