I am having some trouble adding or removing relationships from an entity with AutoDetectChangesEnabled = false
set. Example models and code are as follows:
public class Category : Entity
{
public Guid CategoryId { get; set; }
public virtual ICollection<UserProfile> UserProfiles { get; set; }
public string Name { get; set; }
}
public class UserProfile : Entity
{
public Guid UserProfileId { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public string Name { get; set; }
}
var context = new OfContext();
context.Configuration.AutoDetectChangesEnabled = false;
var userProfile = context.UserProfiles
.Include(up => up.Categories)
.FirstOrDefault(up => up.UserProfileId == new Guid("XXXX"));
var category = context.Categories
.FirstOrDefault(c => c.CategoryId == new Guid("XXXX"));
userProfile.Categories.Add(category);
userProfile.Name = "Updated";
context.Entry(userProfile).State = EntityState.Modified;
context.SaveChanges();
The issue I am having is the addition of the category to the collection is not saved with SaveChanges
. If I have AutoDetectChangesEnabled = true
, this change is picked up and persisted. So I guess the real question is, how do I manually indicate that this collection has been modified.
I know that for properties, I can use the following
.Property(u => u.Name).IsModified
But I am not seeing anything similar to indicate a collection has been changed.