My problem is, that every time when I try querying the database with LinQ methods, I get either Null when using SingleOrDefault(), or an InvalidOperationException when using Single().
Here's my code.
var currentUser = UserManager.FindById(User.Identity.GetUserId());
var post = ApplicationDbContext.Posts
.Include(c => c.Author)
.SingleOrDefault(c => c.Author.Id == currentUser.Id);
if (post == null)
return View(new CertainPost());
I'm suspicious if it ain't wrong that I've used the .Include method on author and in the same time I used the author value to query the DB. If that's the issue, how should I write this properly? Can I in some way use SingleOrDefault() method later in my code, when Author will be loaded? I've been doing it like this, but I find this way very messy
//Such a mess
var posts = ApplicationDbContext.Posts
.Include(c => c.Author)
.ToList();
foreach(var item in posts)
{
if(item.Author.Id == currentUser.Id)
var post = ApplicationDbContext.Posts.SingleOrDefault(c=>c.Id==item.Id)
}
So, what code should I write to compromise on usefulness and optimization?
var post = ApplicationDbContext.Posts.Include(c => c.Author) .ToList().SingleOrDefault(c => c.Author.Id == currentUser.Id);.Include(c => c.Author)and immedeatly ask for it inc => c.Author.Id == currentUser.Idin the same expression. I guess it should load authors 1st, and then I should ask for author Id. But the issue is i don't know how to write it, because if I won't use SingleOrDefault, Single or ToList(), It returns IQueryable<> object, instead of Post object.Author, then you should also have anAuthorIdproperty in yourPostclass - no? Just use that:.SingleOrDefault(p => p.AuthorId == currentUser.Id);public ApplicationUser Author {get;set}instead ofpublic int AuthorId {get;set}Includeis unrelated to what you put as criteria because the query is translated to SQL. May be simply there are no posts for the user you are querying.