fluent-nhibernate automapping foreign key inserts null.
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> GetConventi开发者_StackOverflow中文版ons()
{
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????
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();
Didn´t you wonder why the automapping allowed foreign keys that are created for a one-to-many relation ship to be null in the first place?
So in your example why does the column "workerId" in the table "Indemnification" not have the not null constraint added to it?
I just came across the the problem and I think even though it can be handled in code, it should not be possible at all to insert a null value, right? Any solution for that?
精彩评论