如何通过代码映射IList <string>和NHIbernate映射?</string>

时间:2014-12-18 15:18:04

标签: nhibernate nhibernate-mapping mapping-by-code

我有这个班级

public class Users {
   ...
   public IList<string> Roles {get; set;}
}

必须将其映射到如下所示的数据库架构:

CREATE TABLE Users (
   AppId NVARCHAR(255) NOT NULL,
   ...
   PRIMARY KEY (AppId)
)

CREATE TABLE UserRoles (
   AppId NVARCHAR(255) NOT NULL,
   Role  NVARCHAR(255) NOT NULL,
   PRIMARY KEY (AppId, Role)
)

ALTER TABLE UserRoles ADD CONSTRAINT FK_UserRoles_Users FOREIGN KEY (AppId) REFERENCES Users

如何通过代码映射获得该功能?这个很接近但是#34;角色&#34;列名称错误(NHibernate将其命名为#34; Id&#34;)

public UsersMapping()
{
   Id(x => x.AppId, m => m.Generator(Generators.Assigned));

   Bag(c => c.UserRoless, m =>
   {
      m.Table("UserRoles");
      m.Inverse(false);
      m.Lazy(CollectionLazy.NoLazy);
      m.Key(k =>
      {
         k.Columns(cm => cm.Name("AppId"));
         k.ForeignKey("FK_UserRoles_Users");
      });
   });
}

1 个答案:

答案 0 :(得分:1)

你非常接近,只需要配置元素端:

public UsersMapping()
{
    Table("Users");
    Id(x => x.AppId, m => {
        m.Generator(Generators.Assigned);
        m.Column("AppId");
    });

    Bag(c => c.Roles, m =>
    {
        m.Table("UserRoles");
        m.Inverse(false);
        m.Lazy(CollectionLazy.NoLazy);
        m.Key(k =>
        {
            k.Columns(cm => cm.Name("AppId"));
            k.ForeignKey("FK_UserRoles_Users");
        });
    }, m => {
        // map the element part of the relationship:
        m.Element(el => el.Column("Role"));
    });
}