5

图表

我在这里拉头发,试图弄清楚如何映射下面列出的 UsersRoles 表。我的秃头看起来不太好,所以请帮忙:)

//这里是实体

public class UsersRole
{
    public UsersRole() { }
    public virtual User User { get; set; }
    public virtual Role Role { get; set; }
    public virtual System.Guid UserId { get; set; }
    public virtual System.Guid RoleId { get; set; }


}

//这是目前为止的映射

public class UsersRoleMap : ClassMapping<UsersRole>
{
    public UsersRoleMap()
    {
        Table("UsersRoles");
        Lazy(true);

       // ComponentAsId(); How does this work??


        Property(x => x.UserId, map => map.Column(c =>
            {
                c.Name("UserId");
                c.NotNullable(true);
                c.Length(30);
                c.SqlType("uniqueidentifier");
            }));
        Property(x => x.RoleId, map => map.Column(c =>
            {
                c.Name("RoleId");
                c.NotNullable(true);
                c.Length(30);
                c.SqlType("uniqueidentifier");
            }));
    }
}

请参阅 ComponentAsId 映射中的注释

如果有人能让我走上正轨,请提前感谢

4

3 回答 3

5

您正在寻找的方法称为ComposedId

public class UsersRoleMap : ClassMapping<UsersRole>
{
    public UsersRoleMap()
    {
        ComposedId(map => 
        {
            map.Property(x => x.UserId);
            map.Property(x => x.RoleId);
        });
    }
}

回答您有关如何ComponentAsId工作的问题。你应该有以下类来使用ComponentAsId方法

public class UsersRoleId
{
    public System.Guid UserId { get; set; }
    public System.Guid RoleId { get; set; }
}

public class UsersRole
{
    public virtual User User { get; set; }
    public virtual Role Role { get; set; }
    public virtual UsersRoleId Id { get; set; }
}

现在您可以将 UsersRole.Id 映射为ComponentAsId

public class UsersRoleMap : ClassMapping<UsersRole>
{
    public UsersRoleMap()
    {
        ComponentAsId(x => x.Id);
    }
}

PS:为什么需要映射UsersRoles表?我建议您将用户映射到角色作为多对多关系。

public class UsersMap : ClassMapping<User>
{
    public UsersMap()
    {
        Set(x => x.Roles, x => { }, x => x.ManyToMany());
    }
}

public class RolesMap : ClassMapping<Role>
{
    public RolesMap()
    {
        Set(x => x.Users, x => { }, x => x.ManyToMany());
    }
}
于 2012-08-01T16:15:54.217 回答
1

你真的需要UsersRole作为一个实体吗?通常,当您在数据库表中有一些额外的列时,您只创建一个多对多实体,除了两个 id。

此外,即使您需要创建一个单独的实体,您也不需要拥有UserIdRoleId属性。拥有UserRole属性就足以与 NHibernate 进行映射。

请查看多对多映射,并像这样定义您的用户实体:

public class User
{
    // other properties
    public virtual IList<Role> Roles { get; set; }
}

现在您可以使用映射来映射该角色属性ManyToMany

Bag(x => x.Roles, collectionMapping =>
{
    collectionMapping.Table("UsersRole");
    collectionMapping.Key(k => k.Column("RoleId"));
}, map => map.ManyToMany(p => p.Column("UserId")));

这里还有一个例子

于 2012-08-01T16:13:57.613 回答
0

以下是您可以使用 NHibernate Mapping-By-Code 实现复合键映射的两种方法。

ComponentAsId(x => x.Key, m =>
{
    m.Property(x => x.KeyPart);
    // etc.
});

ComposedId(m =>
{
    m.Property(x => x.KeyPart);
    // other key parts
});
于 2013-09-13T00:03:45.477 回答