mapping (by code - not fluent) an FK column as a list of enums in parent entity
-
25-07-2021 - |
Вопрос
I have an entity class that represents a person and an enum that represents permissions that a person has. I am trying to map this relationship to a database using nhibernate mapping by code without any success.
The code looks like this:
public enum Permissions
{
None = 1,
CanUpdate = 2,
CanInsert = 3,
CanDelete = 4
}
public class Person
{
private ICollection<Permissions> permissions;
public Person()
{
this.permissions = new Collection<Permissions>();
}
public virtual ICollection<Permissions> Permissions
{
get
{
return this.permissions;
}
}
}
public class PersonMap : ClassMapping<Person>
{
public PersonMap()
{
this.Set(
x => x.Permissions,
m =>
{
m.Access(Accessor.Field);
m.Key(k => k.Column("PersonId"));
m.Table("PersonHasPermission");
},
map => map.Element(
p =>
{
p.Column("PermissionId");
p.Type<NHibernate.Type.EnumType<Permissions>>();
}));
}
}
The database tables look like this:
Person
-----------------------
PersonId (PK, uniqueidentifier, not null)
Name (nvarchar(max), not null)
PersonHasPermission
-----------------------
PersonId (PK, FK, uniqueidentifier, not null)
PermissionId (PK, FK, int, not null)
So, with this configuration I do not get any exceptions but whenever I try to fetch the permissions for a person the collection is always empty even though there is data in the database.
I'm hoping that the code above is explains what I am trying to achieve, but do let know if further clarity is required.
Any help with this would be much appreciated. Thanks in advance.
Решение
I am using XML configuration, where I can map even protected or private members. So, surprising for me is that you are not receiving any Exception. Because your Collection does not have any setter (public nor protected). I would expect something like this: NHibernate.PropertyNotFoundException: {"Could not find a setter for property 'Permissions' in class 'Person'"} But maybe fluent is able to translate your mapping from Property to field.
I tried to test your code with a public setter or field (both shown below) and it worked. there is my snippet of xml mapping:
<!-- public or protected setter -->
<bag name="Permissions" inverse="false" lazy="true" table="PresonHasPermission" cascade="all">
<key column="PersonId" />
<element type="Permissions" column="PermissionId" />
</bag>
<!-- accessing the field -->
<bag name="permissions" inverse="false" lazy="true" table="PresonHasPermission" cascade="all"
access="field" >
<key column="PersonId" />
<element type="Permissions" column="PermissionId" />
</bag>
(Leaving your class definition unchanged when mapping to field)