R – How to map a foreign key column in nhibernate

fluent-nhibernatenhibernate-mapping

Actually, the question is more complex than as it is described. I am newbie on nhibernate and I want to map a table with foreign key columns. In most of nhibernate samples the foreign key column assignments are generally implemented by setting the referred entity. I mean, If I have a CategoryId column then I need a Category property and in the samples that I looked, generally Category property is being set. In my case I don't want to set the entity property but the foreign key property instead.

public class Post
{
    public virtual long Id { get; set; };
    public virtual string Content { get; set; };
    public virtual long CategoryId { get; set; };
    public virtual Category Category { get; set; };
}

I don't want to set the category property when I tried to save the Post entity like the sample below.

Post post = new Post { Content = "content", Category = aCategoryEntity };
session.Save(post);

The sample below is the way I want to implement.

Post post = new Post { Content = "content", CategoryId = 3 };
session.Save(post);

How can I get rid off that?

Best Answer

Session.Load was the solution that I've used in here.

Post post = new Post 
{ 
   Content = "content", 
   Category = Session.Load<Category>(categoryId)
};

session.Save(post);
Related Topic