c#EF仅返回具有对象的对象

时间:2016-12-04 17:37:13

标签: c# entity-framework

我正在使用EF 6,有一个帐户,其中一些与设置对象有关系

但并非所有帐户都有设置对象。 如何返回具有设置对象的所有帐户?

 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.
}

我的存储库

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

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

1 个答案:

答案 0 :(得分:1)

添加条件以检查空值

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