Josh Close
Josh Close

Reputation: 23383

Fluent NHibernate Table Per Subclass Saving

This is my setup:

public class Parent
{
    public virtual int Id { get; protected set; }
    public virtual Property1 { get; set; }
}

public class Child : Parent
{
    public virtual Property2 { get; set; }
}

public sealed class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        Id( m => m.Id );
        Map( m => m.Property1 );
    }
}

public sealed class ChildMap : SubclassMap<Child>
{
    public ChildMap()
    {
        KeyColumn( "ParentId" );
        Map( m => m.Property2 );
    }
}

This works great for retrieving data. How do I go about saving this though? I want to create a new child record in the database that's attached to the parent. If i create a new child class that has the same parent values and save, I get errors saying a different object with the same identifier value was already associated with the session: 2, of entity: Child

I guess that makes sense, but how do I create a new Child that has the same parent in the database?

Maybe this isn't possible and I should just do a one to many from the Parent to the Child.

Upvotes: 1

Views: 592

Answers (1)

Diego Mijelshon
Diego Mijelshon

Reputation: 52725

You are misusing inheritance. You can't change the type of an object.

You probably want a one-to-one.

Upvotes: 1

Related Questions