views:

42

answers:

1

I have a class called Worker

 public class Worker : BaseEntity
{
    public virtual int WorkerID { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Indemnification> Indemnifications { get; set; }
}

 public class Indemnification : BaseEntity
{
    public virtual int IndemnificationID { get; set; }
    public virtual string IndemnificationNumber { get; set; }
    //another properties
}

i am using automapping with some conventions

var mappings = new AutoPersistenceModel();
                 mappings.AddEntityAssembly(typeof(Worker).Assembly).Where(GetAutoMappingFilter);
        mappings.Conventions.Setup(GetConventions());
        mappings.Setup(GetSetup());

private Action<IConventionFinder> GetConventions()
    {
        return c =>
        {
            c.Add<PrimaryKeyConvention>();
            c.Add<HasManyConvention>();
            c.Add<TableNameConvention>();
            c.Add<CustomForeignKeyConvention>();
            c.Add<SubClassConvention>();
        };
    }


    public class PrimaryKeyConvention : IIdConvention
    {
        public void Apply(FluentNHibernate.Conventions.Instances.IIdentityInstance instance)
        {
            instance.Column(instance.EntityType.Name + "ID");
            instance.UnsavedValue("0");
        }
    }

    public class HasManyConvention : IHasManyConvention
    {
        public void Apply(FluentNHibernate.Conventions.Instances.IOneToManyCollectionInstance instance)
        {
            instance.Key.Column(instance.EntityType.Name + "ID");
            instance.Cascade.AllDeleteOrphan();
        }
    }

    public class TableNameConvention : IClassConvention
    {
        public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance)
        {
            instance.Table(instance.EntityType.Name);
        }
    }

    public class CustomForeignKeyConvention : ForeignKeyConvention
    {
        protected override string GetKeyName(Member property, Type type)
        {
            return type.Name + "ID";
        }
    }

    public class SubClassConvention : IJoinedSubclassConvention
    {
        public void Apply(FluentNHibernate.Conventions.Instances.IJoinedSubclassInstance instance)
        {
            instance.Table(instance.EntityType.Name);
            instance.Key.Column(instance.EntityType.BaseType.Name + "ID");
        }

    }

the problem is when i save Worker with a list of Indemnifications: the worker is saved, and so the Indemnifications but the foreign key (WorkerID) in the Indemnification table is null????

+1  A: 

I figured out the problem:

when you need to save an entity which has (one to many) relationship, you need to open a transaction and commit it :).

Session.BeginTransaction();
Session.Save(entity);
Session.CommitTransaction();
Nour Sabouny