How to map IList<string> with NHIbernate Mapping by code?

866 Views Asked by At

I have this class

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

I must map it to a DB schema that looks like this:

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

How do I get that with mapping-by-code? This one is close but the "Role" column has the wrong name (NHibernate names it "Id")

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

There are 1 best solutions below

1
On

You were pretty close, just need to configure the element side:

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