Reputation: 11
I'm having the a problem when trying to persist a many to one relationship using Castle ActiveRecord and I hope someone has a better idea than me with this, the idea is to save a single object with a list of dependant objects in a single Save().
I have these classes:
[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; }
}
What I want to do is something like this
var someClass = new SomeClass
{
SomeObjects = new List<AnotherClass>
{
new AnotherClass
{
Something = "Hello"
}
}
};
someClass.Save();
But I get this error:
Hibernate.PropertyValueException: not-null property references a null or transient value
Is there a way I could do that without setting a reference to the parent to every object before calling save?
Thanks!
Upvotes: 1
Views: 725
Reputation: 187
you have to override BeforeSave and/or Save in your class SomeClass
public virtual void Save()
{
using(Transaction t = new Transaction())
{
foreach(AnotherClass a in this.SomeObjects??new AnotherClass[]{})
{
a.Parent = this;
a.Save();
}
base.Save();
}
}
Greetings
Juy Juka
Upvotes: 1