EF4 linq NullReferenceException on non-zero object

First I use the ef4 code with a shared repository. My repository has a select method that looks like this:

public IEnumerable<T> Select(Func<T, bool> predicate)
{
    return objectSet.Where(predicate);
}

I call it with the following code

pushQueueRepository.Select(x => x.User.ID == user.ID && x.PageID == pageID);

* note - pushQueueRepository was created correctly.

When I run this, I get a NullReferenceException. When I look at it in debugging after an exception is thrown, it shows that the error is x.User.ID == user.ID. When I am above x.User, it is zero. However, when I extend x, there is a user object in x.User (not null) that has an identifier.

FYI x is a PushQueue object that is defined as such:

public class PushQueue : IEntity
{
    ...

    [Required]
    public User User { get; set; }

    ... 
}

This does not seem right, am I missing something?

Thank.

+3
3

, PushQueues , : x => x.User.ID == user.ID ​​ , x.User . , EF Lazy Loading. VS, , .

, Select : Func<T, bool>, Expression<Func<T, bool>>. , , , :

public IEnumerable<T> Select(Expression<Func<T, bool>> predicate)
{
    return objectSet.Where(predicate);
}

, select , , . , NullReferenceException , ​​ , EF . PushQueue, :

public virtual User User { get; set; }     
+2

, x , , x.User.

, EF, , , , , . , SQL?

0

, .Include:

pushQueueRepository.Include("User").Select(x => x.User.ID == user.ID && x.PageID == pageID)

. EF, User, , , User.ID.

.Include , , . - :

pushQueueRepository.Include(typeof(User).Name)....

Not very elegant, but at least it is checked by the compiler; -)

0
source

Source: https://habr.com/ru/post/1774462/


All Articles