Hi,
I have 3 tables (Many to Many relationship)
- Resource {ResourceId, Description}
- Role {RoleId, Description}
- 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.