WriteEatSleepRepeat
WriteEatSleepRepeat

Reputation: 3141

remove from collection without load all collection data. confused which collection mapping to use

I have a many-to-many relationship between Assignment and User

When trying to delete an user from an assignment, I see all users are loaded in the collection.

How to I avoid that?

public class User
{
  public virtual int Id { get; private set; }
  public virtual IList<Assignment> Assignments { get; set; }
}


public class Assignment
{
   public virtual int Id { get; private set; }
   public virtual ICollection<User> Users { get; set; }
}

Mappings:

HasManyToMany(user => user.Assignments).Table("UserToAssignment").ParentKeyColumn("UserId").ChildKeyColumn("AssignmentId").Inverse().ExtraLazyLoad();  

HasManyToMany(productAssignment => productAssignment.Users).AsSet().Table("UserToAssignment").ParentKeyColumn("AssignmentId").ChildKeyColumn("UserId").LazyLoad(); 

Calling code:

assignment.Users.Remove(user)

Initially I used Bag instead of Set for Assignment mapping, but when updating it, it was deleting and then reinserting alot of rows in the AssignmentsToUsers table. So I changed to using Set.

But now I see a problem with using Set: it brings all data in memory.

What is the recommended way of doing this?

Upvotes: 1

Views: 320

Answers (2)

Jamie Ide
Jamie Ide

Reputation: 49261

You can't avoid this and I would ignore it if performance is acceptable. If performance is a problem, there are three ways I can think of to tackle it:

  1. If the other side of the collection (User.Assignments) is lighter weight then remove the assignment from the user instead.
  2. Model the many-to-many table and delete the object directly. You would have to be certain that the Users collection is not going to be loaded prior to this because the in-memory representation will still contain the deleted record.
  3. Direct delete using SQL -- this has the same caveat as #2.

Upvotes: 1

Oskar Berggren
Oskar Berggren

Reputation: 5629

You should use extra lazy mode also for Assignment.Users.

Upvotes: 0

Related Questions