fluent-nhibernate自动将外键插入null。

时间:2010-09-04 06:10:03

标签: fluent-nhibernate null foreign-keys one-to-many automapping

我有一个名为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
}

我正在使用自动化与一些约定

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");
        }

    }

问题是当我使用一份赔偿清单保存工人时: 工作人员被保存,所以赔偿但外键(WorkerID)在 赔偿表为空????

2 个答案:

答案 0 :(得分:1)

我发现了问题:

当您需要保存具有(一对多)关系的实体时,您需要打开一个事务并提交它:)。

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

答案 1 :(得分:0)

难道你不知道为什么自动化允许为一对多关系创建的外键首先为空?

因此,在您的示例中,为什么“Indemnification”表中的“workerId”列没有添加非null约束?

我刚刚遇到了问题而且我认为即使它可以在代码中处理,也不应该插入空值,对吧?任何解决方案?