1

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 Answer 1

1

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"));
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but that also creates an id UNIQUEIDENTIFIER not null in the UserRoles table...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.