Несовместимые результаты с использованием Linq's Any() с сущностями
Используя Линка Any()
метод расширения возвращает противоречивые результаты. Я получаю универсальный "Ссылка на объект не установлена на экземпляр объекта".
Я попытался получить записи и сохранить их во временном списке, а затем вызвать Any()
расширение в этом списке, и он работает нормально, но по какой-то причине - для этого конкретного набора сущностей я получаю это поддельное NullReferenceException.
bool result = _Repository.GetAll().Any(p => p.CustomerAccount.Equals(customerAccount)
Ожидаемый результат должен быть истинным или ложным. Вместо этого я получаю исключение NullReferenceException.
Для некоторого дополнительного контекста. Вот несколько строк из моего класса GenericRepository
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private DbContext _Context = null;
private DbSet<T> _Entity = null;
public GenericRepository(DbContext context)
{
_Context = context;
_Entity = _Context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return _Entity.ToList();
}
public T GetById(object id)
{
return _Entity.Find(id);
}
public void Add(T entity)
{
_Entity.Add(entity);
_Context.SaveChanges();
}
public void Update(T entity)
{
_Entity.Attach(entity);
_Context.Entry(entity).State = EntityState.Modified;
_Context.SaveChanges();
}
public void Delete(object id)
{
T existingEntity = _Entity.Find(id);
if(existingEntity != null)
_Entity.Remove(existingEntity);
}
public void Save()
{
_Context.SaveChanges();
}
}
И здесь я вызываю расширение Any и получаю исключение NullReferenceException. Обратите внимание, что я использую это же выражение в других областях, и оно работает безупречно!
static GenericRepository<Customer> = new GenericRepository<Customer>(new MyCoolEntities());
public static bool AnyCustomerExist(string customerAccount)
{
return _Repository.GetAll().Any(p => p.CustomerAccount.Equals(customerAccount));
}
Обновление Вы увидите обсуждение меня и Эми в комментариях. Похоже, есть какая-то запись, где столбец CustomerAccount фактически равен NULL. Вы не можете сравнить с нулем?
Но почему работает приведенный ниже код, если я добавляю его в свой общий репозиторий, а затем вызываю ту же строку, которая не работает, и заменяю ее AnyRecords вместо Any?
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
public bool AnyRecords(Expression<Func<T, bool>> expression)
{
return _Entity.Any(expression);
}
...
Это работает
static GenericRepository<Customer> = new GenericRepository<Customer>(new MyCoolEntities());
public static bool AnyCustomerExist(string customerAccount)
{
return _Repository.GetAll().AnyRecords(p => p.CustomerAccount.Equals(customerAccount));
}
Это не работает, почему?
static GenericRepository<Customer> = new GenericRepository<Customer>(new MyCoolEntities());
public static bool AnyCustomerExist(string customerAccount)
{
return _Repository.GetAll().Any(p => p.CustomerAccount.Equals(customerAccount));
}