views:

1470

answers:

2

Hi, 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 still having the same problem.

when run 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.

here are tables image(sorry but a new user cannot use image tag :S) and the code

 http://img44.imageshack.us/content.php?page=done&l=img44/248/postckn.jpg&via=mupload

 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 ?

+3  A: 

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.

twk
btw, im using Fluent version 1.0, so the .WithTableName() is Table() instead, anyway, i tried to use it without lazyload and other defeintions, but still the same exception :S
Saeedouv
Are you sure it needs to be mapped both sides?
UpTheCreek
A: 

twk Answer is right dude you have something wrong on the map

HasManyToMany<User>

You don't need the Generics Syntax here

BigOmar
I think he does when using Interfaces on his entities. But you are right, i think the error is coming from there.HasManyToMany<User>(x => x.Roles) should be HasManyToMany<Role>(x => x.Roles)
Kohan