Castle ActiveRecord BelongsTo with NotNull = true not-null Exception

时间:2014-04-30 15:00:30

标签: c# nhibernate castle-activerecord

我在尝试使用Castle ActiveRecord持久保持多对一关系时遇到问题,我希望有人比我有更好的想法,我的想法是保存一个带有依赖列表的单个对象单个Save()中的对象。

我有这些课程:

[ActiveRecord("SomeClass")
public class SomeClass : ActiveRecordValidationBase<SomeClass>
{
    [PrimaryKey]
    public virtual long Id { get; set; }

    [HasMany(Cascade = ManyRelationCascadeEnum.AllDeleteOrphan, Inverse = false)]
    public virtual IList<AnotherClass> SomeObjects { get; set; }
}


[ActiveRecord("AnotherClass")
public class AnotherClass : ActiveRecordValidationBase<AnotherClass>
{
    [PrimaryKey]
    public virtual long Id { get; set; }
     [Property(NotNull = true, Unique = true, Length = 70)]
    public string Something { get; set; }

    [BelongsTo("SomeId", NotNull = true)]
    public virtual SomeClass Parent { get; set; }
}

我想做的是这样的事情

var someClass = new SomeClass 
{
    SomeObjects = new List<AnotherClass> 
    {
        new AnotherClass
        { 
           Something = "Hello"
        }
    }
};
someClass.Save();

但是我收到了这个错误:

Hibernate.PropertyValueException: not-null property references a null or transient value

在调用save之前,如果没有为每个对象设置父对象的引用,有没有办法可以做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:0)

你必须在类SomeClass

中覆盖BeforeSave和/或Save
public virtual void Save()
{
  using(Transaction t = new Transaction())
  {
     foreach(AnotherClass a in this.SomeObjects??new AnotherClass[]{})
     {
       a.Parent = this;
       a.Save();
     }
     base.Save();
  }
}

问候

Juy Juka