0

我有一个名为 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)为空????

4

2 回答 2

1

我解决了这个问题:

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

Session.BeginTransaction();
Session.Save(entity);
Session.CommitTransaction();
于 2010-09-08T21:48:56.990 回答
0

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

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

我刚刚遇到了这个问题,我认为即使它可以在代码中处理,也不应该插入一个空值,对吧?有什么解决办法吗?

于 2010-11-21T14:34:52.510 回答