IManyToManyCollectionInstance约定创建额外的表

时间:2013-04-13 00:18:13

标签: c# postgresql nhibernate fluent-nhibernate nhibernate-mapping

我的Fluent NHibernate基于约定的映射,我的StockPurchase实体和我的{​​{1}}实体之间存在多对多关系。

我创建了以下约定:

StockSale

当我使用hbm2ddl函数时,它会按照我想要的方式构建表:

public class ManyToManyLinkedTableConvention : IHasManyToManyConvention
{
    public void Apply(FluentNHibernate.Conventions.Instances.IManyToManyCollectionInstance instance)
    {
        var naming = new NamingStrategy();
        if (StringComparer.InvariantCultureIgnoreCase.Compare(instance.EntityType.Name, instance.OtherSide.EntityType.Name) > 0)
        {
            instance.Table(naming.Quote(
                string.Format(
                    "{0}To{1}",
                    Inflector.Inflector.Pluralize(instance.EntityType.Name),
                    Inflector.Inflector.Pluralize(instance.ChildType.Name))));
            instance.Not.Inverse();
        }
        else
        {
            instance.Inverse();
        }
    }
}
但是,奇怪的是,它也创造了第二张桌子:

CREATE TABLE "StockSalesToStockPurchases"
(
  stocksale_id uuid NOT NULL,
  stockpurchase_id uuid NOT NULL,
  CONSTRAINT fkee886e07285f29f1 FOREIGN KEY (stockpurchase_id)
      REFERENCES "StockPurchases" (stockpurchaseid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fkee886e073b8be3d9 FOREIGN KEY (stocksale_id)
      REFERENCES "StockSales" (stocksaleid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);

为什么要这样做,我该如何阻止它?

1 个答案:

答案 0 :(得分:2)

好的,我发现了如何做到这一点。有人告诉我是否有更好的方法。

public class ManyToManyLinkedTableConvention : IHasManyToManyConvention
{
    public void Apply(IManyToManyCollectionInstance instance)
    {
        var naming = new NamingStrategy();
        string firstName;
        string secondName;

        if (StringComparer.InvariantCultureIgnoreCase.Compare(instance.EntityType.Name, instance.OtherSide.EntityType.Name) >
            0)
        {
            firstName = instance.EntityType.Name;
            secondName = instance.OtherSide.EntityType.Name;
        }
        else
        {
            secondName = instance.EntityType.Name;
            firstName = instance.OtherSide.EntityType.Name;
            instance.Not.Inverse();
        }

        instance.Table(naming.Quote(
            string.Format(
                "{0}To{1}",
                Inflector.Inflector.Pluralize(firstName),
                Inflector.Inflector.Pluralize(secondName))));
    }
}