Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I have the foreign key column in my entity models?

I am coming from the Entity Framework over to NHibernate. When looking at how to create my domain entities I noticed that in some of the examples they don't include the column of the foreign key relationship. Since the Session class contains a Load() method it is possible to just use objects without the trip to the database instead of primary keys. Is this a normal practice when constructing entity models in NHibernate.

Example Entity

public class BlogPost : Entity
{
    public virtual string Name { get; set; }

    //Should this be here
    public virtual int AuthorID { get; set; }

    public virtual Author Author { get; set; }
}

Creating Entity

BlogPost post = new BlogPost
{
    Name = "My first post",
    Author = session.Load<Author>(1) //Avoids hitting the database
};

session.Save(post);

-- OR ---

BlogPost post = new BlogPost
{
    Name = "My first post",
    AuthorID = 1 //Use the id of the object
};

session.Save(post);
like image 256
Stefan Bossbaly Avatar asked Oct 08 '22 03:10

Stefan Bossbaly


1 Answers

You should use full entities / objects instead of having foreign keys.

Foreign keys are database concept. They don't make much sense when you are doing object oriented programming. When doing OOP, you are composing objects together. In your case, a Blog has a collection of Posts. Post has a parent Blog, etc.

Entity IDs are just used to uniquely identify entities.

The whole point of Object-Relational Mapping should be to allow you to use OOP best practices (Object), database best practices (Relational) and not to mix the concepts between them (that's what Mapping part of the name stands for).

Some ORMs are better than others in following this. Hint: NHibernate.

like image 165
Miroslav Popovic Avatar answered Oct 10 '22 08:10

Miroslav Popovic