1

I have 2 objects:

public class Authors
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual IList<Tags> Tags { get; set; }
}

public class Tags
{
    public virtual int Id { get; set; }
    public virtual string TagMark { get; set; }
    public virtual IList<Authors> Authors { get; set; }
}

and mappings for them

public class AuthorsMap : ClassMap<Authors>
{
    public AuthorsMap()
    {
        Id(x => x.Id);

        Map(x => x.FirstName)
            .Length(100)
            .Not.Nullable();

        Map(x => x.LastName)
            .Length(100)
            .Not.Nullable();

        HasManyToMany(x => x.Tags);

    }
}

public class TagsMap : ClassMap<Tags>
{
    public TagsMap()
    {
        Id(x => x.Id);

        Map(x => x.TagMark)
            .Length(100)
            .Not.Nullable();

        HasManyToMany(x => x.Authors)
            .Cascade.All().Inverse(); 
    }
}

But when I want to add new tags to existing author, I don't get anything. Even error is not thrown and, of course tag is not added to relationship table with authors.

for example:

using (var trans.....) {
author.Tags.Add(tagobject)
trans.Commit()
}

while tagobject and author are obtained earlier. I also tried to add like session.SaveOrUpdate(author), but doesn't work... HEELP!

Haris Bašić
  • 1,383
  • 2
  • 12
  • 21
  • Just a note. I wanted to give you a hint, do not use many-to-many if possible. I would suggest to use the pairing object as described here in more details http://stackoverflow.com/a/16827671/1679310 – Radim Köhler Jan 13 '14 at 12:34
  • @Radim: Why not use many-to-many?? It is fully managed by NH and very convenient. – Stefan Steinegger Jan 13 '14 at 12:52
  • @StefanSteinegger Have you ever tried to find Authors by Tags with Many-to-many? With a pairing object you can use subqueries for searching... We've moved from every many-to-many to a full pairing object. Not only each table has its surrogated key, but also you can extend the pairing object. E.g. Order, Importance, IsActive. check **Don't use exotic association mappings** at 24 best practice http://nhforge.org/doc/nh/en/index.html#best-practices – Radim Köhler Jan 13 '14 at 12:53
  • @Radmin: Why is querying a problem? many-to-many is transparent to HQL queries. The "Don't use exotic association mappings"-advise says that real use cases are rare, but not inexistent. As long as you don't need additional properties on the relation, it is much easier. In our project (more then 400 Tables and still growing) we have more than 30 many-to-many relations and had never any issues with them. – Stefan Steinegger Jan 15 '14 at 09:09

1 Answers1

1

You'll need to add a cascade to your Author mapping so that new transient tags are saved when the Author is saved/updated:

HasManyToMany(x => x.Tags)
.Cascade.All();
Ian Nelson
  • 57,123
  • 20
  • 76
  • 103