我已经尝试了几乎所有方法来让 M:M 映射在 S#arp 架构中工作。不幸的是,Northwind 示例项目没有 M:M 覆盖。

在转换为 S#arp 并选择 Fluent NHibernate 的自动映射之前,我的项目中一切都运行良好。我喜欢自动映射,它很好,但是覆盖似乎没有注册。

这一切似乎在内存和测试中都有效,但是当将数据提交到数据库时,没有任何内容被插入到我的 M:M 参考表中。

如果我们取一个类别可以有许多产品的简单样本,并且一个产品可以在许多类别中,我们将有一个名为 CategoryProduct(我不喜欢复数)的表,其中包含 Category_id 和 Product_id 列。

我的自动持久性模型生成如下:

return AutoPersistenceModel
    .MapEntitiesFromAssemblyOf<Category>()
    .Where(GetAutoMappingFilter)
    .ConventionDiscovery.Setup(GetConventions())
    .WithSetup(GetSetup())
    .UseOverridesFromAssemblyOf<AutoPersistenceModelGenerator>();

类别的映射覆盖如下所示:

public class CategoryMap : IAutoMappingOverride<Category>
{
    public void Override(AutoMap<Category> mapping)
    {
        mapping.Id(x => x.Id, "Id")
            .WithUnsavedValue(0)
            .GeneratedBy.Identity();

        mapping.Map(x => x.Name).WithLengthOf(50);

        mapping.Map(x => x.Depth);

        mapping.HasMany<Category>(x => x.Children)
            .Cascade.All()
            .KeyColumnNames.Add("Parent_id")
            .AsBag()
            .LazyLoad();

        mapping.HasManyToMany<Posting>(x => x.Products)
            .WithTableName("CategoryProduct")
            .WithParentKeyColumn("Category_id")
            .WithChildKeyColumn("Product_id")
            .Cascade.All()
            .AsBag();
    }
}

并且该产品具有这样的映射覆盖:

public class ProductMap : IAutoMappingOverride<Product>
{
    public void Override(AutoMap<Product> mapping)
    {
        mapping.Id(x => x.Id, "Id")
            .WithUnsavedValue(0)
            .GeneratedBy.Identity();

        mapping.Map(x => x.Title).WithLengthOf(100);
        mapping.Map(x => x.Price);
        mapping.Map(x => x.Description).CustomSqlTypeIs("Text");
        mapping.References(x => x.Category).Cascade.All();

        mapping.HasMany<ProductImage>(x => x.Images).Inverse().Cascade.All().LazyLoad();

        mapping.HasManyToMany<Category>(x => x.Categories)
            .WithTableName("CategoryProduct")
            .WithParentKeyColumn("Product_id")
            .WithChildKeyColumn("Category_id")
            .Inverse()
            .AsBag();
    }
}

我尝试了多种构建 M:M 映射的组合,但没有任何效果。

文章 有人建议重新编译 S#arp 并更新 FHN,我尝试了这个,但是最新的 FHN 代码与 S#arp 使用的代码看起来有很大不同。修复了所有中断冲突,但仍然不起作用。

希望其他人已经遇到并解决了 S#arp 的 M:M 自动映射覆盖问题。

有帮助吗?

解决方案

设法解决了这个问题,结果发现这是一个S#arp初学者错误。

为了保存 ManyToMany 数据,控制器方法需要为其分配 [Transaction] 属性。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top