I have a fixed-length data file need to persistence into database. I use a XML file to define the length for the fields and use a list of FieldItem class to store the data.
class FieldItem { public string ObjectName {get; set;} public string ObjectProperty {get; set;} public string ObjectValue {get; set;} public FieldItem() { } }
So the FieldItem will look like
var fieldItem = new FieldItem { ObjectName = 'Company', ObjectProperty = 'Name', ObjectValue = 'ABC Corp.' }
After get the list of FieldItem, I will do refection to create Company and other domain objects to save them into database.
But before they are saved into database, I have some business rules needed to be applied to validate the data line. My data line will look like:
var fieldItemList = new List<FieldItem>(){ new FieldItem { ObjectName='Company', ObjectProperty = 'Name', ObjectValue = 'ABC' } new FieldItem{ ObjectName = 'Product', ObjectProperty = 'ProductCode', ObjectValue ='XYZ0123' new FieldItem{ ObjectName = 'Product', ObjectProperty = 'ProductName', ObjectValue ='Christmas Tree' } // other FieldItem objects... }
For example, my rule is to check if the company == ‘ABC’ and ProductCode == ‘XYZ0123’. Those rules are created by users and stored as a string in the database. What I am doing right now is to use Microsoft’s System.Linq.Dynamic to evaluate the rule, such as
string validationRule = ' (ObjectName == \'Company\' And ObjectProperty=\'CompanyName\' And ObjectValue = \'ABC Corp.\') And (ObjectName == \'Product\' And ObjectProperty=\'ProductCode\' And ObjectValue = \'XYZ0123\') '; var query = fieldItemList.AsQuerable().Where(validationRule);
then check if it has one row return to tell if that data row has passed the rule or not. Obviously, it is too verbose. Do you have any better suggestion? What should I do if I only like my rule expression like: ‘Company.CompanyName = ‘ABC Corp.’ and Product.ProductCode = ‘XYZ001”?
RE: ‘What should I do if I only like my rule expression like: ‘Company.CompanyName = ‘ABC Corp’ and Product.ProductCode = ‘XYZ001”?
Map this user-friendly query: ‘Company.CompanyName = ‘ABC Corp’ AND Product.ProductCode = ‘XYZ001” to something that is friendly to your data structure(FieldItem):
‘ObjectName = ‘Company’ AND ObjectProperty = ‘CompanyName’ AND ObjectValue = ‘ABC Corp’ OR ObjectName = ‘Product’ AND ObjectProperty = ‘ProductCode’ AND ObjectValue = ‘XYZ001”
How to know if the user’s rules passed the rules or not? Count the number of conditions, if it matches the count of results of fieldItemList.AsQueryable().Where(itemFieldFriendlyQuery), then the data line is valid based on user’s rules.
some rudimentary mapper(use regular expression or roll your own parser to make the following code truly valid):