Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with the following Fluent NHibernate Mapping?

I have 3 tables (Many to Many relationship)

  1. Resource {ResourceId, Description}
  2. Role {RoleId, Description}
  3. Permission {ResourceId, RoleId}

I am trying to map above tables in fluent-nHibernate. This is what I am trying to do.

var aResource = session.Get<Resource>(1); // 2 Roles associated (Role 1 and 2)
var aRole = session.Get<Role>(1);
aResource.Remove(aRole); // I try to delete just 1 role from permission.

But the sql generated here is (which is wrong)

Delete from Permission where ResourceId = 1
Insert into Permission (ResourceId, RoleId) values (1, 2);

Instead of (right way)

    Delete from Permission where ResourceId = 1 and RoleId = 1

Why nHibernate behave like this? What wrong with the mapping? I even tried with Set instead of IList. Here is the full code.

Entities

public class Resource
{
    public virtual string Description { get; set; }
    public virtual int ResourceId { get; set; }
    public virtual IList<Role> Roles { get; set; }

    public Resource()
    {
        Roles = new List<Role>();
    }
}

public class Role
{
    public virtual string Description { get; set; }
    public virtual int RoleId { get; set; }
    public virtual IList<Resource> Resources { get; set; }

    public Role()
    {
        Resources = new List<Resource>();
    }
}

Mapping Here

// Mapping ..
public class ResourceMap : ClassMap<Resource>
{
    public ResourceMap()
    {
        Id(x => x.ResourceId);
        Map(x => x.Description);
        HasManyToMany(x => x.Roles).Table("Permission");
    }
}

public class RoleMap : ClassMap<Role>
{
    public RoleMap()
    {
        Id(x => x.RoleId);
        Map(x => x.Description);
        HasManyToMany(x => x.Resources).Table("Permission");
    }
}

Program

    static void Main(string[] args)
    {
        var factory = CreateSessionFactory();
        using (var session = factory.OpenSession())
        {
            using (var tran = session.BeginTransaction())
            {
                var aResource = session.Get<Resource>(1);
                var aRole = session.Get<Role>(1);
                aResource.Remove(aRole);
                session.Save(a);
                session.Flush(); 
                tran.Commit();
            }
        }
    }
    private static ISessionFactory CreateSessionFactory()
    {
        return Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2008
            .ConnectionString("server=(local);database=Store;Integrated Security=SSPI"))
            .Mappings(m => 
                m.FluentMappings.AddFromAssemblyOf<Program>()
                .Conventions.Add<CustomForeignKeyConvention>())
            .BuildSessionFactory();
    }

    public class CustomForeignKeyConvention : ForeignKeyConvention
    {
        protected override string GetKeyName(FluentNHibernate.Member property, Type type)
        {
            return property == null ? type.Name + "Id" : property.Name + "Id";
        }
    }

Thanks, Ashraf.

like image 632
ashraf Avatar asked Mar 26 '10 01:03

ashraf


1 Answers

nHibernate thinks all relationship is bi-directional until you declare parent/child.So you need "Inverse". Without that, it takes two steps as "Delete" all and "Recreate" with the new value, especially "Bag" type (default). For ManyToMany, changing entity collection type (HashSet/Set) won't affect the mapping to "Bag".It only works for HasMany. You need specifically say "AsSet" in map. (IList/ICollection) maps to "Bag". If you want List, you need to have it "AsList" in map. But List requires additional index column in the table.

// Mapping .. 
public class ResourceMap : ClassMap<Resource> 
{ 
    public ResourceMap() 
    { 
        Id(x => x.ResourceId); 
        Map(x => x.Description); 
        HasManyToMany(x => x.Roles).AsSet().Inverse().Table("Permission");
    } 
} 

public class RoleMap : ClassMap<Role> 
{ 
    public RoleMap() 
    { 
        Id(x => x.RoleId); 
        Map(x => x.Description); 
        HasManyToMany(x => x.Resources).AsSet().Cascade.SaveUpdate().Table("Permission");
    } 
} 

Also, I would put Fetch.Select().LazyLoad() for lazyload.

like image 157
stoto Avatar answered Oct 04 '22 02:10

stoto