tags:

views:

34

answers:

2

I have a class called Entry. This class as a collection of strings called TopicsOfInterest. In my database, TopicsOfInterest is represented by a separate table since it is there is a one-to-many relationship between entries and their topics of interest. I'd like to use nhibernate to populate this collection, but since the table stores very little (only an entry id and a string), I was hoping I could somehow bypass the creation of a class to represent it and all that goes with (mappings, configuration, etc..)

Is this possible, and if so, how? I'm using Fluent Nhibernate, so something specific to that would be even more helpful.

+2  A: 
public class Entry
{
    private readonly IList<string> topicsOfInterest;

    public Entry()
    {
      topicsOfInterest = new List<string>();
    }

    public virtual int Id { get; set; }

    public virtual IEnumerable<string> TopicsOfInterest
    {
       get { return topicsOfInterest; }
    }
}

public class EntryMapping : ClassMap<Entry>
{
  public EntryMapping()
  {  
     Id(entry => entry.Id);
     HasMany(entry => entry.TopicsOfInterest)
       .Table("TableName")
       .AsList()
       .Element("ColumnName")
       .Cascade.All()
       .Access.CamelCaseField();
  }
}
Paco
Thanks, this is exactly what I ended up doing.
Chris
A: 

I had a similar requirement to map a collection of floats.

I'm using Automapping to generate my entire relational model - you imply that you already have some tables, so this may not apply, unless you choose to switch to an Automapping approach.

Turns out that NHibernate will NOT Automap collections of basic types - you need an override.

See my answer to my own question How do you automap List or float[] with Fluent NHibernate?.

I've provided a lot of sample code - you should be able to substitute "string" for "float", and get it working. Note the gotchas in the explanatory text.

Tom Bushell