views:

176

answers:

1

I can't get my head around why this isn't working..

I have a relatively clean entity model consisting of POCOs created with DDD in mind (while probably not following most rules even loosely).

I am using Fluent NHibernate to do the mapping. I am also using SchemaExport to create the database schema, with minimum input from me on how to do it. NHibernate is free to choose the best way.

I have two entities with Many-to-many relationships with each other (non-interesting code removed); MediaItem and Tag; MediaItems can have many tags, Tags can be applied to many MediaItems, and I want collections on both sides so I can easily get at stuff.

(A bit of a formatting issue below, sorry)

  • MediaItem:

    public class MediaItem
    {
    
    
    private IList<Tag> _tags;
    
    
    public virtual long Id { get; set; }
    
    
    public virtual string Title { get; set; }
    
    
    public virtual IEnumerable<Tag> Tags { get { return _tags; } }
    
    
    public MediaItem()
    {
        _tags = new List<Tag>();
    }
    
    
    public virtual void AddTag(Tag newTag)
    {
        _tags.Add(newTag);
        newTag.AddMediaItem(this);
    }
    

    }

  • Tag:

    public class Tag {

    private IList<MediaItem> _mediaItems;
    public virtual long Id { get; set; }
    public virtual string TagName { get; set; }
    public virtual IEnumerable<MediaItem> MediaItems { get { return _mediaItems; } }
    
    
    public Tag()
    {
        _mediaItems = new List<MediaItem>();
    }
    
    
    protected internal virtual void AddMediaItem(MediaItem newItem)
    {
        _mediaItems.Add(newItem);
    }
    

    }

I have tried to be smart about only exposing the collections as IEnumerable, and only allowing adding items through the methods. I also hear that only one side of the relationship should be responsible for this - thus the contrived AddMediaItem() on Tag.

The MediaItemMap looks like this:

public class MediaItemMap : ClassMap<MediaItem>
{
    public MediaItemMap()
    {
        Table("MediaItem");

        Id(mi => mi.Id);

        Map(mi => mi.Title);

        HasManyToMany<Tag>(mi => mi.Tags)
            .Access.CamelCaseField(Prefix.Underscore)
            .Cascade.SaveUpdate();
    }
}

The Tag mapping looks like this:

public class TagMap : ClassMap<Tag>
{
    public TagMap()
    {
        Table("Tag");

        Id(t => t.Id);

        Map(t => t.TagName);

        HasManyToMany<MediaItem>(mi => mi.MediaItems)
            .Access.CamelCaseField(Prefix.Underscore)
            .Inverse();
    }
}

Now I have some test code that drops the database schema, recreates it (since I am shotgun debugging my brains out here), and then runs the following simple code:

Tag t = new Tag { TagName = "TestTag" };
MediaItem mi = new MediaItem { Title = "TestMediaItem" };

mi.AddTag(t);

var session = _sessionFactory.OpenSession();

session.Save(mi);

Yep, this is test code, it will never live past the problem in this post.

The MediaItem is saved, and so is the Tag. However, the association between them is not. NHibernate does create the association table "MediaItemsToTags", but it doesn't attempt to insert anything into it.

When creating the ISessionFactory, I specify ShowSQL() - so I can see all the DDL sent to the SQL server. I can see the insert statement for both the MediaItem and the Tag tables, but there is no insert for MediaItemsToTags.

I have experimented with many different versions of this, but I can't seem to crack it. Cascading is one possible problem, I've tried with Cascade.All() on both sides, Inverse() on both sides etc., but no dice.

Can anyone tell me what is the correct way to map this to get NHibernate to actually store the association whenever I store my MediaItem?

Thanks!

+1  A: 

You need to define the many-to-many table and parent and child key columns:

public class MediaItemMap : ClassMap<MediaItem>
{
    public MediaItemMap()
    {
        Table("MediaItem");

        Id(mi => mi.Id);

        Map(mi => mi.Title);

        HasManyToMany<Tag>(mi => mi.Tags)
            .Table("MediaItemsToTags").ParentKeyColumn("Id").ChildKeyColumn("Id")
            .Access.CamelCaseField(Prefix.Underscore)
            .Cascade.SaveUpdate();
    }
}

The syntax is identical in TagMap because both key columns are named "Id".

Jamie Ide
Hi,Thanks for your suggestion. I thought ParentKeyColumn and ChildKeyColumn were used for naming the columns in the table defined by Table(). So I was really hopeful for this, but unfortunately it gave me an error when I tried to initialize the ISessionFactory: Repeated column in mapping for collection: PhotoAlbumLibrary.Entities.MediaItem.Tags column: Id So while this could support my theory, I will gladly admit I know way too little about this. I wouldn't think, however, it would be a requirement to name the identity fields for each entity differently?
Rune Jacobsen
Okey, I just did a test. In the mapping for the Id fields I changed the column name like this: Id(mi => mi.Id, "MediaItemId"); (and the same for Tag, only with "TagId"). I also made the changes you suggested, adding the Table, ParentKeyColumn and ChildKeyColumn with the proper names, and unforutnately, I am still in the same situation - no attempt is made by NHibernate to insert anything into the MediaItemsToTags table. I also tried doing a session.Save on the tag object just in case, but no effect.
Rune Jacobsen
I missed this before, but you need to call `session.Flush()` after `session.Save(mi)`. The MediaItem and Tag objects are saved without flushing because NHibernate needs to insert them so that auto-generated keys are created by the database. I am confident that the changes you've already made plus calling `session.Flush()` will work.
Jamie Ide
Jamie - your confidence is spot on! :) This would normally be taken care of by the repository code, but the repo isn't there yet, I am simply hacking away right at the ISession. A flush did it - thank you very much for the help, it is highly appreciated!
Rune Jacobsen
Ok, just in the interest of being very specific.. I rolled back most of the changes, and it turns out that everything actually worked the way I had it originally (that way, NHibernate came up with the association table and columns itself), as long as I either flushed the session object or wrapped the whole thing in a transaction.
Rune Jacobsen
I'm glad you were able to work it out. I suspect that Fluent NHibernate conventions are responsible for creating the association class and mapping the columns. In my code I pass the ISession into repository constructors (manual dependency injection) and let the calling code control the session and transaction. This makes it possible for multiple repository methods to be part of the same unit-of-work/transaction.
Jamie Ide