开发者

How can I stop Fluent NHibernate from creating foreign keys

开发者 https://www.devze.com 2023-01-11 18:28 出处:网络
I got a polymorphic relationship like the following example: public class A { public virtual Guid Id { get; set; }

I got a polymorphic relationship like the following example:

public class A
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
}

Class B & C contining a List of A's:

public class B/C
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<A> As { get; set; }
    public virtual SomeParent Parent { get; set; }
}

My goal are queries like

session.Linq<B>().Where(x => x.Parent == someParent && x.As.Contains(someA));

Currently I configured a Many-To-Many relation between B => A and C => A using a shared link table because I want to have all my links in one table. In this examle NH shema export creates 4 tables, A, B, C and ChildToA.

HasManyToMany(x => x.As)
            .AsBag()
            .Table("XX_ChildToA")
            .ParentKeyColumn("Child_ID")
            .ChildKeyColumn("A_ID")
            .Cascade.All()

This works fine as long as you use only one the child types because shema export generates a foreign key restricting the "Chil开发者_如何学Cd_ID" to IDs of whatever table it hits first while exporting (B in this case).

var b = session.Get<B>(id);
b.As.Add(someA);
tx.Commit(); // works fine

var c = session.Get<C>(id);
c.As.Add(someA);
tx.Commit(); // crashes because of FK constraint

Can I stop FluentNHibernate from creating this FK? While I searched google for this problem I noticed HBM samples with foreign-key="no" attributes in many-to-one relationships. So NHibernate should be able to solve this, right? However I would like to keep my fluent mappings because I can create a generic base mapping class for all my child types this way and currently all our mappings are FNH mappings.


This should do it:

HasManyToMany(x => x.As)
  .ForeignKeyConstraintNames("no", "no");


I'm not entirely familiar with FluentNHibernate, but I'm assuming you could set this custom attribute on your mapping for the collection using something like:

.SetAttribute("foreign-key", "no")

0

精彩评论

暂无评论...
验证码 换一张
取 消