maddisoj
maddisoj

Reputation: 587

Object referenced by many, without own property

I have a class that is referenced by many other classes:

class Foo
{
    // Some properties
}

class Bar
{
    public Foo Foo { get; set; }
}

I can map this relationship on the Bar end:

class BarMap : ClassMap<Bar>
{
    public BarMap()
    {
        References(b => b.Foo).Cascade.All();
    }
}

This works when I am deleting a Bar object but I am getting foreign key conflicts if I try and delete a Foo object. I understand this is because NHibernate doesn't know that there are Bars relying on it, so happily tries to delete the Foo and not the Bars.

I know I can do something along the lines of:

class Foo
{
    public IList<Bar> Bars { get; set; }

    // some properties
}

class FooMap : ClassMap<Foo>
{
    public FooMap()
    {
        HasMany(f => f.Bars)
            .Inverse()
            .Cascade.AllDeleteOrphans();
    }
}

Is there a way to map Foo so that it knows about the inverse many-to-one relationship without adding a property to Foo? I don't really want to add a collection to Foo for each type of object referencing it.

Upvotes: 0

Views: 40

Answers (1)

Fr&#233;d&#233;ric
Fr&#233;d&#233;ric

Reputation: 9854

I think I have correctly understood your aim, and I fear the answer is you cannot do that easily.

You may try using IInterceptor or event combined with some analysis of the meta-model NHibernate has generated from your mapping (see ISessionFactory.GetAllClassMetadata), but this would probably requires a bunch of work hours.

Upvotes: 1

Related Questions