2016-04-29 17 views
1

我們應用程序中的業務層使用CSLA.NET。我有業務類名爲Invoice和InvoiceItem(從CSLA BusinessBase的子類派生)和InvoiceItemList(派生自CSLA BusinessBindingListBase的子類)。CSLA.NET BusinessBindingListBase的最小/最大計數規則

發票類有項目的屬性,聲明如下:

private static readonly PropertyInfo<InvoiceItemList> ItemsProperty = 
RegisterProperty<InvoiceItemList>(o => o.Items, RelationshipTypes.Child); 


public InvoiceItemList Items 
{ 
    get 
    { 
     return GetProperty(ItemsProperty); 
    } 
    private set 
    { 
     SetProperty(ItemsProperty, value); 
    } 
} 

我想實現一個CSLA業務規則,確保發票沒有保存而不至少一個項目。所以,我創建了一個MinCount規則,派生自CSLA PropertyRule並將其應用於Items屬性。

BusinessRules.AddRule(new MinCount(ItemsProperty, 1)); 

的問題是,當的SetProperty叫上ItemsProperty,被稱爲只有一次(在DataPortal_Create)此規則僅觸發。在創建時沒有任何項目,因此該規則正確地將該對象標記爲無效。但是,當InvoiceItem對象添加到/從項目屬性中刪除時,規則不會被觸發。結果發票對象保持無效,並且不被保存。

對於從BusinessBindingListBase(或BusinessListBase)派生的屬性,實現規則(例如Min/Max Count規則)的正確方法是什麼?

回答

1

我寫了下面的代碼來觸發我的最小/最大規則。

protected override void OnChildChanged(ChildChangedEventArgs e) 
{ 
    base.OnChildChanged(e); 

    // We are only interested in some change in a List property 
    if (e.ListChangedArgs == null || e.ChildObject == null) return; 

    // We are only interested in addition or removal from list 
    if (e.ListChangedArgs.ListChangedType != ListChangedType.ItemAdded 
     && e.ListChangedArgs.ListChangedType != ListChangedType.ItemDeleted) 
     return; 

    // Find property by type 
    var t = e.ChildObject.GetType(); 
    var prop = FieldManager.GetRegisteredProperties().FirstOrDefault(p => p.Type == t); 

    // Raise property change, which in turn calls BusinessRules.CheckRules on specified property 
    foreach (prop != null) 
     PropertyHasChanged(prop); 
} 

上面的代碼不會處理具有多個相同類型的List屬性的場景。代碼可以使用Where(代替FirstOrDefault)來遍歷所有這些屬性。缺點是,這種變化會因其他屬性不必要地觸發。

+0

您可以通過執行if(e.ChildObject is InvoiceItemList){// do stuff}來過濾特定列表上的代碼, – Andy