Bunnynut
Bunnynut

Reputation: 1328

NHibernate one-to-many removing related records

I have three tables with the following structure:

Todo
    Id
    Name

User
    Id
    Name

TodoUser
    Id
    TodoId
    UserId
    Status

For Todo.ResponsibleUsers I have created the following mapping:

private IList<TodoUser> responsibleUsers = new List<TodoUser>();
[Bag(0, Name = "ResponsibleUsers", Cascade = CascadeStyle.AllDeleteOrphan, Table = "TodoUser", Inverse = true)]
[Key(1, Column = "TodoId")]
[OntToMany(2, ClassType = typeof(TodoUser))]
public virtual IList<TodoUser> ResponsibleUsers {
    get { return responsibleUser; }
    set { responsibleUsers = (IList<TodoUser>)value; }
}

Does the property ResponsibleUsers have to be of type IList<TodoUser> or can it also be of type List<TodoUser>? I would like to do something like todo.ResponsibleUsers.RemoveAll(itemsToRemove); which is not possible on an IList<TodoUser>

Upvotes: 1

Views: 27

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

To answer the question:

Does the property ResponsibleUsers have to be of type IList<TodoUser> or can it also be of type List<TodoUser>?

Check the doc:

Chapter 6. Collection Mapping

6.1. Persistent Collections

NHibernate requires that persistent collection-valued fields be declared as a generic interface type, for example:

public class Product
{
    private string serialNumber;
    private ISet<Part> parts = new HashSet<Part>();

    public ISet<Part> Parts
    {
        get { return parts; }
        set { parts = value; }
    }

    public string SerialNumber
    {
        get { return serialNumber; }
        set { serialNumber = value; }
    }
}

The actual interface might be System.Collections.Generic.ICollection<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IDictionary<K, V>, System.Collections.Generic.ISet<T>

So, yes, we must use interface.

To solve the issue with

I would like to do something like todo.ResponsibleUsers.RemoveAll(itemsToRemove);

We can implement some custom extension method as

public static class Ext
{
    public static void RemoveAll(this IList<T> list, IEnumerable<T> toRemove)
    {
        ... // remove items matching toRemove from the list
    }

Upvotes: 1

Related Questions