How to make Parent Object invalid if child collection is empty

How to make Parent Object invalid if child collection is empty

Old forum URL: forums.lhotka.net/forums/t/8048.aspx


shawndewet posted on Thursday, November 26, 2009

In the typical scenario of orderheader having a MyLines Property As OrderDetailCollection.

What businessrule can I add to OrderHeader that makes it InValid (for saving) if the count of MyLines = 0?
I was thinking along the use of a CommonRules.IntegerMinValue rule set to 0, but to which property of OrderHeader could I attach it, such that it is re-evaluated when the MyLines property has a line added to it, and of course reflects as being broken if the last object in MyLines is removed?

Marjon1 replied on Thursday, November 26, 2009

You could always just override the IsVslid() property and have it do the following:
return MyBase.IsValid AndAlso _OrderLines.Count > 0

peteisace replied on Thursday, November 26, 2009

i've done this, but i'm not sure how much of a hack it is...

declare a new custom rule

private static bool ValidateMyLines(object target, RuleArgs e)
{
OrderDetail detail = (OrderDetail)target;
if(detail.ReadProperty(myLinesProp).Count == 0)
{
e.Description = "There must be at least one line for the order.";
return false;
}

return true;
}

// Add the rule to the business rules

protected override void AddBusinessRules()
{
this.ValidationRules.AddRule(ValidateMyLines, new RuleArgs(myLinesProp));
}

// Ensure it's called when the collection changes

protected override void OnChildChanged(ChildChangedEventArgs e)
{
base.OnChildChanged(e);
this.ValidationRules.CheckRules("MyLines");
}

like i said, probably a bit hacky, but it works :)

alef replied on Sunday, November 29, 2009

With the solution of Marjon you have less code but you have no information why the object is not saved. The object is just invalid and will not be saved.

With the solution of peteisace a brokenrule will be added to the BrokenRulesColection. When using the ErrorTreeView from CslaContrib this information will be displayed. Also when using the cslaActionExtender (AutoShowBrukenRules = True) you'll have a messagebox of the broken rules.

Maybe you need to call also CheckRules() in the dataportal_create method.

 

Lhotka: is this the correct way to implment this?

 

Copyright (c) Marimer LLC