Reputation: 39484
I have the following EF 3.0 query using InMemoryDatabase
:
IQueryable<Post> posts = _context.Posts.AsNoTracking();
posts = posts.Where(x => x.Enabled);
IQueryable<PostModel> models = null;
try {
models = jobs
.Select(x => new PostModel {
Id = x.Id,
Enabled = x.Enabled,
Category = x.Category == null ? null : new CategoryModel {
Id = x.Category.Id,
Name = x.Category.Name
}
);
var result = await responses.ToListAsync();
} catch (Exception e) {
var ex = e;
}
Initially posts
have 2 items. After the filter Where(x => x.Enabled)
I get one item.
But at the end result
has no items ... It seems the existing item disappeared in the projection.
Then I tried the following (Removed the Category part):
models = jobs
.Select(x => new PostModel {
Id = x.Id,
Enabled = x.Enabled
);
var result = await responses.ToListAsync();
Now result has one item as expected ...
Any idea what might be wrong? I am really lost on this one.
Upvotes: 0
Views: 53
Reputation: 39484
This problem is hard to identify and I am posting the solution which might be useful for others in the future ...
In the Post
model configuration Category
property / relationship was set as Required.
When I added posts to context
one of them had, by mistake, Category
set to null
.
If I was using SQL Server I would get an error when saving the context.
But because I am doing Testing and I was using InMemoryDatabase the invalid post was accepted.
And that led to the really strange error on the query ...
Conclusion:
In EF 3.0 (and previous versions) the Model is not validated at C# level.
So when using InMemoryDatabase wrong models will be saved and let to unexpected errors in queries.
There is also a Github issue in Entity Framework Core 3.0: https://github.com/aspnet/EntityFrameworkCore/issues/10613
Upvotes: 1