Clone method "losing" business rules

Clone method "losing" business rules

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


sgraham posted on Friday, October 16, 2009

I am using 2005 (Visual Studio, .NET and CSLA).

I have a business object (which is a grandchild but I don't think that matters) that has 8 instance rules added every time it's insantiated (via the AddInstanceBusinessRules override).  There is a 9th instance rules that is added sometimes (depending on other data).

The problem occurs when the 9th rule IS part of the business object and it is saved.  The Clone method seems to create a clone object that only has the 8 instances rules and not the 9th.

Is this by design?  Is there a workaround?

Any info would be greatly appreciated!

rsbaker0 replied on Saturday, October 17, 2009

CLSA clones by serializing and then deserializing the object. So, nothing marked as [Nonserialized] is cloned except that which is restored in OnDeserializedHandler. This includes the instance business rules.

However, it turns out that OnDeserializedHandler does call AddInstanceBusinessRules again. So, what you'll need to do is handle your "special" data related case in your AddInstanceBusinessRules method. (If you're already adding your 9th rule here, then I'm mistaken somewhere)

The issue I had was that AddInstanceBusinessRules is initially called in the BusinessBase constructor, so it can't do anything special based on the content of a derived class.

However, this is possibly not the case when OnDeserializedHandler is called, as I'd think the derived class properties are in place at that time, so you could test for your special case and add the extra rule. (This would mean AddInstanceBusinessRules would act one way when the object is initially constructed and differently when called from OnDeserializedHandler)

sgraham replied on Monday, October 19, 2009

I had wondered if that had something to do with it.  Thanks for confirming!  I was reading some other posts and went one better and made it a type rule instead of an instance rule.  The type rules checks the special data prior to checking the actual rule.  Thanks for your guidance!!

Copyright (c) Marimer LLC