Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

orm - Fluent NHibernate HasManyToMany() Mapping

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: Exception occurred getter of project.Entities.User.UserName ---> System.Reflection.TargetException: Object does not match target type.

This is an image of the tables:

Tables

and the code

 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();

    }

here is the code, most examples on the web and the Fluent Nhibernate mappings page are written in the same way, so any ideas ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

    }

Such a definitions works for me. Check this first then decorate with LazyLoading and some other properties.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...