D-W
D-W

Reputation: 5341

c# EF Only return objects that have objects

I'm using EF 6, have an Account that some have an relationship to a Setting object

However not all accounts have a setting object. How can I return all Accounts that have a setting object?

 using (IUnitOfWork uw = _uwf.Create())
            {
 Dictionary<string, Account> accounts;
accounts = uw.Account.All.Where(ac=>ac.Setting.IsEnabled).ToDictionary(a => a.Id, a => a); <--- this is the problem, just want the ones that have a Setting otherwise im getting null reference thrown.
}

My Repository

public class AccountRepository : MarkForDeleteRepository<DomainObjects.Account>, IAccountRepository
    {

        public override IEnumerable<Account> All
        {
            get
            {
                return
                    RepositorySet.Include("Country")
                        .Include("Setting")
            }
        }

Upvotes: 0

Views: 20

Answers (1)

Damith
Damith

Reputation: 63065

Add where condition to check the null

accounts = uw.Account.All.Where(ac=>ac.Setting !=null && ac.Setting.IsEnabled).ToDictionary(a => a.Id, a => a);

Upvotes: 1

Related Questions