Search code examples
c#collectionscastle-activerecord

Is it possible to have a List<string> as a property on an active record class


Is it possible to have a HasMany relationship of a basic type such as String, on an ActiveRecord class, without the need for creating another entity such as (TodoListItem) to hold the value.

[ActiveRecord]
public class TodoList
{

  [PrimaryKey]
  public int Id
  {
    get { return _id; }
    set { _id = value; }
  }

  [HasMany(typeof(string)]
  public IList<string> Items
  {
    get { return _items; }
    set { _items= value; }
  }
}

Can anyone help?


Solution

  • Yes, you can do this. You can map a one-to-many relation to a built-in or simple type (value type or string) rather than a persisted type.

    You'll need to specify the ColumnKey, Table and Element params in the HasMany attribute declaration to get it to wire up properly. You have to have a surrogate key column so the AR can handle updates and cascades, and then Element tells AR which column in the table holds the simple value it will use to make the list.

    [HasMany(typeof(string), Table="ToDoList_Items", 
             ColumnKey = "ListItemID", Element = "Item")]
    public IList<string> Items { get; set; }
    

    (or something similar - I haven't got a compiler handy on this box to check it; but per the API docs it ought to work.)

    Speaking of which, if you haven't already had a look, http://api.castleproject.org is kinda indispensible for any work with the Castle stack.