Praveen
Praveen

Reputation: 41

FluentNhibernate mapping when having two primary keys

I use Fluent Nhibernate for my C# application and I have a very basic question. I would like to know what an NHibernate mapping class should look like when we have multiple primary keys.

Here is an example showing how I implement mapping and other model classes:

CREATE TABLE Students(
   id   INT              NOT NULL,
   name VARCHAR (20)     NOT NULL,
   age  INT              NOT NULL,       
   PRIMARY KEY (id)
);

public class Students
{
   public virtual int      ID   { get; set; }
   public virtual string   Name { get; set; }
   public virtual int      Age  { get; set; }
}


public class StudentMap : ClassMap<Students>
{
    public AchivementMasterMap()
    {
       Id(x => x.ID).Column("id");
       Map(x => x.Name).Column("name");
       Map(x => x.Age).Column("age");
       Table("Students");
     }
}

Let's assume we have two primary keys on Student table like this

CREATE TABLE Students(
       id   INT              NOT NULL,
       name VARCHAR (20)     NOT NULL,
       age  INT              NOT NULL,       
       PRIMARY KEY (id,name)
);

So how to write mapping class for the above table?

Upvotes: 3

Views: 2146

Answers (1)

F5 F5 F5
F5 F5 F5

Reputation: 179

You don't have 2 primary keys, you appear to have a composite primary key. I think you can use Fluent NHibernate CompositeId - something like this:

public class StudentMap : ClassMap<Students>
{
    public StudentMap()
    {
            CompositeId()
                .KeyProperty(x => x.name, "id")
                .KeyProperty(x => x.name, "name");

            ...

Upvotes: 1

Related Questions