你好我使用流利的nhibernate我的映射有问题:
public ProductMap()
{
Id(x => x.ProductID);
Map(x => x.ProductName);
Map(x => x.QuantityPerUnit);
Map(x => x.ReorderLevel);
Map(x => x.SupplierID);
Map(x => x.UnitPrice);
Map(x => x.UnitsInStock);
Map(x => x.UnitsOnOrder);
Map(x => x.CategoryID);
Map(x => x.Discontinued);
References(x => x.Category).Column("CategoryID");
References(x => x.Supplier).Column("SupplierID");
Table("dbo.Products");
}
public SupplierMap()
{
Id(x => x.SupplierID);
Map(x => x.Address);
Map(x => x.City);
Map(x => x.CompanyName);
Map(x => x.ContactName);
Map(x => x.ContactTitle);
Map(x => x.Country);
Map(x => x.Fax);
Map(x => x.HomePage);
Map(x => x.Phone);
Map(x => x.PostalCode);
Map(x => x.Region);
HasMany(x => x.Products)
.KeyColumn("SupplierID")
.Inverse()
.Cascade.All();
Table("dbo.Suppliers");
}
public CategoryMap()
{
Id(x => x.CategoryID);
Map(x => x.CategoryName);
Map(x => x.Description);
Map(x => x.Picture);
HasMany(x => x.Products)
.KeyColumn("CategoryID")
.Inverse()
.Cascade.All();
Table("dbo.Categories");
}
当我尝试做的时候:
var sessionFactory = SessionFactory.CreateSessionFactory();
using (var session = sessionFactory.OpenSession())
{
Product fresh = new Product()
{
ProductName = "AddFromNhibernate",
SupplierID = 3,
CategoryID = 5,
QuantityPerUnit = "1kg pcg",
UnitPrice = (decimal) 35,
UnitsInStock = (short?) 15,
UnitsOnOrder = 0,
ReorderLevel = null,
Discontinued = true
};
using (session.BeginTransaction())
{
session.Save(fresh);
session.Transaction.Commit();
}
}
我收到了System.IndexOutOfRangeException。 我的映射有什么问题?当我尝试获取一些数据时工作正常,但添加失败。我想在ProductMap中专门针对参考物业参考,但它没有帮助。
答案 0 :(得分:1)
我注意到你两次映射了一些列。
以ProductMap
为例:
public ProductMap()
{
(...)
Map(x => x.SupplierID);
(...)
Map(x => x.CategoryID);
References(x => x.Category).Column("CategoryID");
References(x => x.Supplier).Column("SupplierID");
(...)
}
在这种情况下,如果要保留原始ID 和引用(因为它们映射到数据库表中的同一列),您应绕过其中一个中的插入/更新
我的意思是:
public ProductMap()
{
(...)
Map(x => x.SupplierID).Not.Insert().Not.Update();
(...)
Map(x => x.CategoryID).Not.Insert().Not.Update();
References(x => x.Category).Column("CategoryID");
References(x => x.Supplier).Column("SupplierID");
(...)
}
如果你没有这样做,你可能会得到NHibernate开始设置插入/更新参数时所描述的Exception
。