0

i have this 2 class

public class Product {
    public virtual Guid Id {get; set;}
    public virtual string Name {get; set;}
    public virtual Description Description {get; set;}
}

public class Description {
    public virtual Guid Id {get; set;}
    public virtual string Suggestion {get; set;}
    public virtual string Composition {get; set;}
}

i've try to map the class with this Mapper class:

public class ProductMap : ClassMap<Product>
{
    public ProductMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        References(x => x.Description).ForeignKey("Id");
    }
}

Description was related to Product with same Id, so e.g Product with Id = 1 will have description in table with Id = 1. Now i try to read data from the table with this:

using (var session = factory.OpenSession())
{
    var testProduct = session.Query<Product>().Where(p => p.Id == 2).Single();
    lblValue.Text = testProduct.Description.Composition;
}

but i get error exception

InnerException: System.Data.SqlClient.SqlException
       Message=Invalid column name 'Description_id'.

i know i've put something wrong in mapper constructor. Could u guys help me how to map this correctly. i dont want to put field Description_id in table Product. Thanks

Dion Dirza
  • 2,575
  • 2
  • 17
  • 21

2 Answers2

1

Change your ProductMap to be like this:

public class ProductMap : ClassMap<Product>
{
  public ProductMap()
  {
    Id(x => x.Id);
    Map(x => x.Name);
    References(x => x.Description).Columns("Id");
  }
}

This tells nHibernate to join Products to Description using the "Id" column of the Product entity to the column defined as Id in the DescriptionMap (which also needs to be set to "Id"). Incase you don't already have it I have created a DescriptionMap class which you will also need:

public class DescriptionMap : ClassMap<Description>
{
  public DescriptionMap ()
  {
    Id(x => x.Id);
    Map(x => x.Suggestion);
    Map(x => x.Composition);
  }
}
connectedsoftware
  • 6,987
  • 3
  • 28
  • 43
1

What CSL mentioned should work, but I would add that the Column Name is actually the second parameter of the References method, so you can simply do this.

public class ProductMap : ClassMap<Product>
{
  public ProductMap()
  {
    Id(x => x.Id);
    Map(x => x.Name);
    References(x => x.Description, "Id");
  }
}
Nick Albrecht
  • 16,607
  • 10
  • 66
  • 101
  • thanks, it works for read. but now i have problem when insert. – Dion Dirza May 22 '13 at 14:54
  • To fix the insert problem, change the Id mappings on both classes to be Id(x=>x.Id).GeneratedBy.Assigned(); This tells nHibernate that the application will specify the Id and it won't be auto-generated by an Identity column in the DB. – connectedsoftware May 22 '13 at 15:15