Fluent NHibernate(具有自动映射)不保存多对多连接表值
我不完全是 NHibernate 专家,所以这可能是对该部门缺乏了解。我有两个具有多对多关系的简单实体
public class Category
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual bool Visible { get; set; }
public virtual IList<Product> Products { get; set; }
}
,
public class Product
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual decimal Price { get; set; }
public virtual bool Visible { get; set; }
public virtual IList<Category> Categories { get; set; }
}
我的配置是
public static void BuildFactory()
{
_factory = Fluently.Configure()
.Database(
MsSqlConfiguration
.MsSql2008
.ConnectionString(_connectionString)
.ShowSql()
)
.Mappings(m =>
m.AutoMappings.Add(
AutoMap.AssemblyOf<Database>()
.Where(t => t.Namespace == "FancyStore.Models.Catalog")
.Override<Product>(k =>
k.HasManyToMany(x => x.Categories)
.Table("ProductsToCategories")
.ParentKeyColumn("Product_id")
.ChildKeyColumn("Category_id")
.Cascade.AllDeleteOrphan())
.Override<Category>(k =>
k.HasManyToMany(x => x.Products)
.Table("ProductsToCategories")
.ParentKeyColumn("Category_id")
.ChildKeyColumn("Product_id")
.Cascade.AllDeleteOrphan().Inverse())
)
)
.ExposeConfiguration(SetConfiguration)
.BuildConfiguration()
.BuildSessionFactory();
}
所以我开始时没有覆盖(在一些谷歌搜索建议后添加它们),并使用 ExportSchema 生成我的架构。 ExportSchema 了解多对多关系(即使没有覆盖),因为它生成了一个连接表 (ProductsToCategories
)。
我想添加一些简单的测试数据,所以我这样做了,
using (var db = new Repository<Category>())
{
for (int i = 0; i < 6; i++)
{
var cat = new Category
{
Name = "Things" + i,
Description = "Things that are things",
Visible = true,
Products = new List<Product>()
};
for (int k = 0; k < 6; k++)
{
var prod = new Product
{
Name = "Product" + k,
Description = "Product for " + cat.Name,
Visible = true,
Categories = new List<Category>(new[] { cat })
};
cat.Products.Add(prod);
}
db.Save(cat);
}
}
这可以正确保存产品和类别,但它不会保存连接表中的任何关系。查看对category.Products的调用生成的sql,它实际上是在连接表中查找产品(并且找不到任何产品,因为它是空的)
任何帮助将不胜感激:-)
编辑 :删除了相反的问题,问题仍然发生:(
编辑2:
这是目录和产品的映射文件(注意:这个名字有点傻,但这只是一个快速原型式的交易)
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="FancyStore.Models.Catalog.Product, FancyStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="`Product`">
<id name="Id" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Id" />
<generator class="identity" />
</id>
<property name="Name" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Name" />
</property>
<property name="Description" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Description" />
</property>
<property name="Price" type="System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Price" />
</property>
<property name="Visible" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Visible" />
</property>
<bag cascade="all-delete-orphan" inverse="true" name="Categories" table="ProductsToCategories">
<key>
<column name="Product_id" />
</key>
<many-to-many class="FancyStore.Models.Catalog.Category, FancyStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<column name="Category_id" />
</many-to-many>
</bag>
</class>
</hibernate-mapping>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="FancyStore.Models.Catalog.Category, FancyStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="`Category`">
<id name="Id" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Id" />
<generator class="identity" />
</id>
<property name="Name" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Name" />
</property>
<property name="Description" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Description" />
</property>
<property name="Visible" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Visible" />
</property>
<bag cascade="all-delete-orphan" name="Products" table="ProductsToCategories">
<key>
<column name="Category_id" />
</key>
<many-to-many class="FancyStore.Models.Catalog.Product, FancyStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<column name="Product_id" />
</many-to-many>
</bag>
</class>
</hibernate-mapping>
I am not exactly an NHibernate expert, so this may be a lack of understanding in that department. I have two simple entities with a many-to-many relationship
public class Category
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual bool Visible { get; set; }
public virtual IList<Product> Products { get; set; }
}
and
public class Product
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual decimal Price { get; set; }
public virtual bool Visible { get; set; }
public virtual IList<Category> Categories { get; set; }
}
My configuration is
public static void BuildFactory()
{
_factory = Fluently.Configure()
.Database(
MsSqlConfiguration
.MsSql2008
.ConnectionString(_connectionString)
.ShowSql()
)
.Mappings(m =>
m.AutoMappings.Add(
AutoMap.AssemblyOf<Database>()
.Where(t => t.Namespace == "FancyStore.Models.Catalog")
.Override<Product>(k =>
k.HasManyToMany(x => x.Categories)
.Table("ProductsToCategories")
.ParentKeyColumn("Product_id")
.ChildKeyColumn("Category_id")
.Cascade.AllDeleteOrphan())
.Override<Category>(k =>
k.HasManyToMany(x => x.Products)
.Table("ProductsToCategories")
.ParentKeyColumn("Category_id")
.ChildKeyColumn("Product_id")
.Cascade.AllDeleteOrphan().Inverse())
)
)
.ExposeConfiguration(SetConfiguration)
.BuildConfiguration()
.BuildSessionFactory();
}
So I started without the overrides (added them in later after some googling suggested it), and am generating my schema with ExportSchema. ExportSchema knows about the many to many relationship (even without the overrides), because it generated a join table (ProductsToCategories
).
I wanted to add some simple test data, so I did it like this
using (var db = new Repository<Category>())
{
for (int i = 0; i < 6; i++)
{
var cat = new Category
{
Name = "Things" + i,
Description = "Things that are things",
Visible = true,
Products = new List<Product>()
};
for (int k = 0; k < 6; k++)
{
var prod = new Product
{
Name = "Product" + k,
Description = "Product for " + cat.Name,
Visible = true,
Categories = new List<Category>(new[] { cat })
};
cat.Products.Add(prod);
}
db.Save(cat);
}
}
This saves products and categories properly, but it does not save any of the relationships in the join table. Looking at the sql a call to category.Products generates, it is actually looking in that join table for products (and cant find any, since it is empty)
Any help would be greatly appreciated :-)
EDIT: Removed an inverse, problem still happening :(
EDIT2:
Here are the mapping files for catalog and product (note: the name is kind of silly, but this is just a quick prototype-ish sort of deal)
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="FancyStore.Models.Catalog.Product, FancyStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="`Product`">
<id name="Id" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Id" />
<generator class="identity" />
</id>
<property name="Name" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Name" />
</property>
<property name="Description" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Description" />
</property>
<property name="Price" type="System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Price" />
</property>
<property name="Visible" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Visible" />
</property>
<bag cascade="all-delete-orphan" inverse="true" name="Categories" table="ProductsToCategories">
<key>
<column name="Product_id" />
</key>
<many-to-many class="FancyStore.Models.Catalog.Category, FancyStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<column name="Category_id" />
</many-to-many>
</bag>
</class>
</hibernate-mapping>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="FancyStore.Models.Catalog.Category, FancyStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="`Category`">
<id name="Id" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Id" />
<generator class="identity" />
</id>
<property name="Name" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Name" />
</property>
<property name="Description" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Description" />
</property>
<property name="Visible" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Visible" />
</property>
<bag cascade="all-delete-orphan" name="Products" table="ProductsToCategories">
<key>
<column name="Category_id" />
</key>
<many-to-many class="FancyStore.Models.Catalog.Product, FancyStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<column name="Product_id" />
</many-to-many>
</bag>
</class>
</hibernate-mapping>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我可能是错的,但看起来你将双方的关系标记为“反向”。
您应该仅对关系的一侧执行此操作,并确保在另一侧调用
Save
。另外,我认为在保存之前,双方的关系都必须有效(除了您已经执行的操作之外,还将
cat
添加到prod.Categories
中)。诚然,我对这些关系的理解是模糊的,但这是我几个月来的研究得出的结论(并解决了我自己的一些问题)。
I might be mistaken, but it looks like you marked the relationship as "inverse" for both sides.
You should do this for only one side of the relationship, and make sure you call
Save
on the other one.Also, I believe the relationship needs to be valid on both sides before you save (add
cat
toprod.Categories
, in addition to what you're already doing).My understanding of these kinds of relationships is admittedly fuzzy, but this is what my research over the months has come up with (and solved some of my own problems).
@马特·布里格斯,我已经弄清楚了。您必须将一个关系设置为 Inverse() 并保存另一个实体,添加对两个实体的引用 (prod.Categories.Add() + cat.Products.Add()) 并提交事务。除非您提交,否则不会生成连接表的查询。 – HeavyWave 5 月 13 日 12:43
@Matt Briggs, I've figured it out. You have to set one relationship as Inverse() and save the other entity, add references to both entities (prod.Categories.Add() + cat.Products.Add()) and commit the transaction. Unless you commit the query for the join table won't be generated. – HeavyWave May 13 at 12:43
你在关联的错误一侧有逆。逆的意思是“对方管理这个关联”。
您需要的是删除类别上的 Inverse 并将其放在产品上,或者将产品更改为“拥有”实体,如下所示:
You have inverse on the wrong side of the association. Inverse means "the other side manages this association".
What you need is either to remove Inverse on Category and put it on Product, or change Product to be the 'owning' entity, like this:
如果您要在自动映射之前先对产品和类别应用流畅映射,该怎么办?例如,
通过配置,
What about if you were to apply the fluent mappings for Product and Category first, before the automapping. For example,
with configuration,