Search code examples
c#nhibernatenhibernate-mappingnhibernate-mapping-by-code

NhiberNate Map by code does not contain a definision for 'id'


I have played around with NHiberNate, I got it to work with xml definision, but I'm stuck in my Map by Code test. I have the following code :

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
using NHibernate.Mapping;


namespace NHibernatePets
{
public class Pet
{
    virtual public int id { get; set; }
    virtual public string PetName { get; set; }
    virtual public string Species { get; set; }
    virtual public DateTime Birthday { get; set; }

    virtual public string Speak()
    {
        return "Hi.  My name is '" + PetName + "' and I'm a " + Species    + " born on " + Birthday + ".";
    }
}

public class PetMap : ClassMapping<Pet>
{
    public PetMap()
    {
        table("Pet");

        Lazy(true);
        Id(x => x.Id, map => map.Generator(Generators.Identity));
        Property(x => x.Petname, map => map.NotNullable(true));
        Property(x => x.Species, map => map.NotNullable(true));
        Property(x => x.Birthday, map => map.NotNullable(true));
    }

When I hit f5 i gives me following error mesage

Error 15 'NHibernatePets.Pet' does not contain a definition for 'Id' and no extension method 'Id' accepting a first argument of type 'NHibernatePets.Pet' could be found (are you missing a using directive or an assembly reference?) }

My plan was to be able to do a query on the PET database as this

using (ISession session = OpenSession())
{
    IQuery query = session.CreateQuery(" FROM Pet");
    IList<Pet> pets = query.List<Pet>();
    Console.Out.WriteLine("pets.Count = " + pets.Count);
    pets.ToList().ForEach(p => Console.WriteLine(p.Speak()));
}

It worked when I used xml to map the table. What do i do wrong here ?


Solution

  • C# is case sensitive and because the ID property is named "id"

    public class Pet
    {
        virtual public int id { get; set; }
    

    We cannot map it as Id

    Id(x => x.Id... // there is no Id on x === Pet
    

    So, to follow common naming conventions in C# just change property name to Id

    public class Pet
    {
        //virtual public int id { get; set; }
        virtual public int Id { get; set; }