Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 639
Praveen Avatar asked Mar 01 '26 21:03

Praveen


1 Answers

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

            ...
like image 114
F5 F5 F5 Avatar answered Mar 03 '26 10:03

F5 F5 F5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!