问题描述
在使用多对多关系的Fluent NHibernate示例中,我遇到了问题.我试图找出类似案例的例子,但发现了很多吨,但我仍然遇到同样的问题.
I am having a problem in Fluent NHibernate example utilizing the Many-to-Many relationships. I tried to find out examples on a similar case, and I found tons, but I'm still having the same problem.
运行测试项目时,会引发以下异常:
When running the test project, the following exception is thrown:
NHibernate.PropertyAccessException:项目.Entities.User.UserName的吸气剂发生异常---> System.Reflection.TargetException:对象不匹配目标类型.
NHibernate.PropertyAccessException: Exception occurred getter of project.Entities.User.UserName ---> System.Reflection.TargetException: Object does notmatch target type.
这是表格的图像:
和代码
public UsersMap()
{
this.Table("Users");
Id(x => x.UserName).Column("Username").GeneratedBy.Assigned();
Map(x => x.FirstName);
Map(x => x.LastName);
Map(x => x.Password);
Map(x =>x.EMail);
Map(x => x.Title);
Map(x => x.Division);
HasManyToMany<User>(x => x.Roles)
.Table("UserInRoles").ParentKeyColumn("Username")
.ChildKeyColumn("Usernamepk")
.Cascade.SaveUpdate().LazyLoad();
}
public RolesMap()
{
this.Table("Roles");
Id(x => x.ID).GeneratedBy.Assigned().Column("ID");
Map(x => x.RoleName).Length(50);
HasManyToMany<User>(x => x.Users)
.Table("UserInRoles").ParentKeyColumn("ID")
.ChildKeyColumn("RoleIdpk").Cascade.SaveUpdate().LazyLoad();
}
这是代码,网络上的大多数示例和Fluent Nhibernate映射页面都是以相同的方式编写的,所以有什么想法吗?
here is the code, most examples on the web and the Fluent Nhibernate mappings page are written in the same way, so any ideas ?
推荐答案
关于我在项目中使用的代码,我将以这种方式定义您的manyTomany关系:
Regarding to code I am using in my project I would define your manyTomany relations this way:
public UsersMap()
{
...
HasManyToMany(x => x.Roles)
.WithTableName("UserInRoles")
.WithParentKeyColumn("Usernamepk")
.WithChildKeyColumn("RoleIdpk");
}
public RolesMap()
{
...
HasManyToMany(x => x.Users)
.WithTableName("UserInRoles")
.WithParentKeyColumn("RoleIdpk")
.WithChildKeyColumn("Usernamepk");
}
这样的定义对我有用.首先选中此选项,然后使用LazyLoading和其他一些属性进行装饰.
Such a definitions works for me.Check this first then decorate with LazyLoading and some other properties.
这篇关于流利的NHibernate HasManyToMany()映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!