views:

214

answers:

3

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?

A: 

Your entity "Post," doesn't need both CategoryId and a Category property.

Typically you would map Category as well, and your Post mapping would relate the two using the foreign key.

You could try something like this then

session.Save(new Post(){ Category = new Category(){ Id = 3 } });

Hope this helps.

Mark Dickinson
Your suggest is in my mind but I'm looking for an exact solution for that. By the way I'm using fluent-nhibernate for mappings. I guess there is a method or something else that I missed which could do something like that.
yapiskan
You need to think about Liam's answer. The code has no way of knowing if the category id is valid, so it will violate the foreign key and throw an exception.
Mark Dickinson
Usually when you feel like you are working against a technology, it is because you are. If you have the chance to redesign so that you can work with a Category object as a property of Post, it will save you lots of headache. :)
Mark Dickinson
I had a co-worker to persuade. And I did :) Dealing with objects is the right way of get rid of that.
yapiskan
A: 

I don't know if this is possible for NHibernate. The whole point of an ORM is to deal with objects, not RDMS foreign keys.

liammclennan
I know, this is not a best practice and it is exceptional for ORM but I need that anyway.
yapiskan
A: 

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

related questions