0
votes

I'd like to ask some questions about Fluent NHibernate as I'm developing in it almost a year but still there are some things which I don't get.

  1. First questions is about entities as the title says. Why do I make them virtual?

  2. A senior developer told me, that when I have a list of other objects in another one, I should initialize it in constructor, example:

    public class Category
    {
     public virtual int Id { get; set; }
     public virtual string Name { get; set; }
    
     public virtual IEnumerable<Equipment> Equipments { get; set; }
    
     public Category()
     {
         Equipments = new List<Equipment>();
     }
    }
    

    The first thing here is that I have a warning "Virtual member called in constructor" - I googled that but didn't really understood the problem with this. And the second part of question is: do I MUST initialize this list? Maybe I don't MUST but it's a good approach: if so, why?

  3. Third question is about mappings, this is my way for above class:

    public  class CategoryMap: ClassMap<Category>
    {
      public CategoryMap()
      {
        Id(x => x.Id);
        Map(x => x.Name);
        HasMany(x => x.Equipments);
      }
    }
    

    And in some examples I have seen a one line of code:

    Table("Category");
    

    When do I need to specify the table?

----EDIT Thanks for the answer, but now I have to clear something more, about the lazy loading. I read this: http://www.codeproject.com/Articles/652556/Can-you-explain-Lazy-Loading

And you can see a class Customer with private field _Orders and a public getter of that object (which also initialize the _Orders list). Can you please tell me if this is a better approach than mine? If yes, how should I change my code? (fields are virtual because of Fluent NH.)

1

1 Answers

2
votes
  1. Properties need to be virtual for nhibernate so that they can be substituted with proxies (required for lazy-loading)
  2. You don't have to do that.However, it is a good practice to initialize collections in the constructor so that you don't get null suddenly in the code. For example , consider following code

    var category = session.Get<Category>(1);
    //without c-tor this line will throw exception as collection is null
    var totalEquipments = category.Equipments.Count();
    

    So either initialize it in constructor or keep writing this

    var totalEquipments = (category.Equipments == null) ? 0 : category.Equipments.Count()
    
  3. This is to specify that entity Category should be mapped to table named Category. It can be used if entity name doesn't match default name or to make it clear where you want to store entities (see fluent-wiki for details on other attributes)