Reputation: 1555
I'm having a problem here.
How you can see on the code below, I have 2 objects: "Pedidos" and "Categoria". A "Pedido" contais ONE "Categorie".
I did the test Method and both Pedidos and Categoria are stored on DB. Great!
But...... The field "Pedido.Categoria" is empty. Where am I going wrong?
ENTITIES:
public class Categoria : IKeyed<int>{
public virtual int Id { get; set; }
public virtual string Nome { get; set; }};
public class Pedido : IKeyed<int>{
public virtual int Id { get; set; }
public virtual string Assunto { get; set; }
public virtual Categoria Categoria { get; set; }
public virtual IList<Interacao> Interacao { get; set; }
public virtual void addCategoria(Categoria categoria)
{Categoria = categoria;}
};
MAPPINGS:
public class PedidoMap : ClassMap<Pedido>
{
PedidoMap()
{
Table( "z1_pedido" );
Id( x => x.Id );
Map( x => x.Assunto );
References( x => x.Categoria ).Column( "id" );
HasMany( x => x.Interacao ).LazyLoad().Inverse().Cascade.All();
}
}
public class CategoriaMap : ClassMap<Categoria>
{
CategoriaMap()
{
Table( "z1_categoria" );
Id( x => x.Id );
Map( x => x.Nome ).Column("nome");
}
}
TEST METHOD:
public void AddTest()
{
Repository<Pedido> repository = new Repository<Pedido>( unitOfWork.Session );
Repository<Categoria> catRepo = new Repository<Categoria>( unitOfWork.Session );
Categoria cat = new Categoria
{
Nome = "2",
};
Pedido pedido = CreatePedido( string.Format( "Pedido {0}", 1 ), 2,cat );
repository.Add( pedido );
catRepo.Add( cat );
unitOfWork.Commit();
}
private static Pedido CreatePedido(string assunto, int numberofInteractions, Categoria cat)
{
Pedido pedido = new Pedido
{
Assunto = assunto,
Categoria = cat,
};
pedido.addCategoria( cat );
return pedido;
}
Thks, guys.
Upvotes: 1
Views: 97
Reputation: 608
This is the problem I think:
References( x => x.Categoria ).Column( "id" );
With the default conventions the primary key column will be named Id
but in this case it will also be foreign key to the Categoria table (SQL identifiers are case insensitive) which will result in a very weird relation (each Pedido is related to a Categoria with the same id if any.)
The column name specified on a Reference refers to the foreign key column to use in the entity itself since the primary key column in the other entity can be inferred from the mapping of that entity. So in order to get a normal many-to-one relation you should change the column name for the Categoria reference (to for example "categoria_id"):
public class PedidoMap : ClassMap<Pedido>
{
PedidoMap()
{
Table( "z1_pedido" );
Id( x => x.Id );
Map( x => x.Assunto );
References( x => x.Categoria ).Column( "categoria_id" );
HasMany( x => x.Interacao ).LazyLoad().Inverse().Cascade.All();
}
}
Upvotes: 3