Nestor
Nestor

Reputation: 8384

Entity Framework's strange eager loading

I use Entity Framework 6.1.3. I have an Entity, and it has a reference to another Entity:

using System;
using System.Collections.Generic;

public partial class Users
{
    public System.Guid UserID { get; set; }   
    public System.Guid ExtID { get; set; }       
    public Nullable<System.Guid> UserData_UserDataID { get; set; }   
    public virtual UserData UserData { get; set; }

}

I use the following EF query to get all of them:

 UserList = new ObservableCollection<Users>((from user in db.Users.Include("UserData") 
                                             where user.ExtID == ExtId1   
                                             orderby user.UserData.Title 
                                             select user).ToList());

My grid shows the users correctly when it first loads.

Later, I remove some of the users by using this:

      db.Users.Attach(SelectedUser);
      db.Users.Remove(SelectedUser);
      UserList.Remove(SelectedUser);

If the user chooses to Cancel the operation, I undo the changes of the context:

var changedEntries = dbContext.ChangeTracker.Entries().Where(x => x.State != EntityState.Unchanged).ToList();
foreach (var entry in changedEntries.Where(x => x.State == EntityState.Deleted))
      {
        entry.State = EntityState.Unchanged;
      }

Then I reload the list, using the query above.

Strangely, the new List is not the same as the original: the removed items' UserData fields are null.

I use this code to check:

UserList.Count(item => item.UserData == null)

On the first run, its result is 0. After the remove, the result is equal with the number of the removed items.

Can you tell me why? How could I force them to reload?

Upvotes: 1

Views: 183

Answers (1)

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

Can you tell me why?

That's because changing entitystate to Unchanged would not reload the dbcontext. you need to manually reload the context something like this:

var changedEntries = dbContext.ChangeTracker.Entries().Where(x => x.State != EntityState.Unchanged).ToList();
foreach (var entry in changedEntries.Where(x => x.State == EntityState.Deleted))
{
    //No need to set entry to Unchanged
    entry.Reload();
}

Upvotes: 2

Related Questions