I would like to use NHibernate Automapper to map the following class:
public class AdminUser: Identity, IIdentityWithRoles
{
public virtual IList<Role> Roles { get; set; }
}
Problem is that Automapper creates a manytoone relationship within the schema where role has adminuserId on it. But I need roles to be ManyToMany with this. NOTE I cannot change the Role class to have IList on it because it is in a seperate library and has no knowledge of AdminUser.
What I really want to do is to be able to add an atrribute thus:
public class AdminUser: Identity, IIdentityWithRoles
{
[ManyToMany]
public virtual IList<Role> Roles { get; set; }
}
which will force automapper to do this. Is it possible to adjust my Automapper config to look for this attribute or is there something built into FluentNhibernate which already does this job?
Many thanks for any help you can provide.
UPDATE --
OK thanks for the pointer (upvoted) but now I am stuck here:
public class ManyToManyConvention : AttributePropertyConvention<ManyToManyAttribute>
{
protected override void Apply(ManyToManyAttribute attribute, IPropertyInstance instance)
{
How can I now say that this property should be a many to may relationship
}
}
public class ManyToManyAttribute : Attribute
{
}
You have to write an override for a default AdminUser
mapping:
public class AdminUserOverride : IAutoMappingOverride<AdminUser>
{
public void Override(AutoMapping<AdminUser> mapping)
{
mapping.HasManyToMany(x => x.Roles); // and possibly other options here
}
}
And register it with your AutoMapping
:
Fluently.Configure()
.Database(/* database config */)
.Mappings(m =>
m.AutoMappings
.Add(AutoMap.AssemblyOf<AdminUser>().UseOverridesFromAssemblyOf<AdminUser>()))
If this occurs more than in this one place, you can replace it with an Convention
, but this is a bit more complicated.