2016-11-18 105 views
1

当我保存一个具有一对多(HasMany)关系的实体时,数据库上的寄存器是重复的。 PedidoVenda表流利的一对多映射nhibernate重复寄存器

图片:

enter image description here

图片ItemPedidoVenda表:

enter image description here

我可以在此看图片,这个问题是因为ItemPedidoVenda的ID是一个向前那PedidoVenda id。但是这是自动保存的。这可能是什么?

我在类的属性是这些:

public class PedidoVenda { 

    public virtual IList<ItemPedidoVenda> Itens { get; set; } 
    ... 
} 

public class ItemPedidoVenda { 

    public virtual PedidoVenda Pedido { get; set; } 
    ... 
} 

映射器:

PedidoVendaMapper:

HasMany(x => x.Itens) 
     .KeyColumn("PEDIDO_ID") 
     .Inverse() 
     .Cascade.All(); 

ItemPedidoVendaMapper:

References(x => x.Pedido) 
      .Column("PEDIDO_ID").Cascade.All(); 

回答

0

当添加ITEMP edidoVenda实例添加到PedidoVenda中的项目列表中,您必须确保将ItemPedidoVenda中的Pedido属性设置为正确的实例。

我很确定你没有这样做。

我主要做的是阻止我的API(程序员:)的用户不能直接向列表中添加项目。相反,我编写了一个将项目添加到列表的Addxxx方法。

接下来,您必须确保您使用正确的集合类型。我建议一组你的情况

像这样:

public class PedidoVenda { 

    private ISet<ItemPedidoVenda> _itens = new HashedSet<ItemPedidoVenda>(); 

    // The public property which returns the collection is a REadOnlyCollection so the user cannot mess around with it. 
    public ReadOnlyCollection<ItemPedidoVenda> Itens 
    { 
     get 
     { 
      return new List<ItemPedidoVenda>(_itens).AsReadOnly(); 
     } 
    } 

    public void AddPedido(ItemPedidoVenda item) 
    { 
     if(_itens.Contains(item) == false) 
     { 
      item.Pedido = this; // Here, make sure that the reference is filled out. 
      _itens.Add(item); 
     } 
    } 

}