C# Dynamically determine class properties based on configuration for comparison

184 views Asked by At

I have a configuration defined for duplicate check on each property in my model below

public class ConfigurationModel
{
    public GroupValue Value1 { get; set; }
    public GroupValue Value2 { get; set; }
    public GroupValue Value3 { get; set; }
    public GroupValue Value4 { get; set; }
    public GroupValue Value5 { get; set; }
}
public class GroupValue
{
    public bool duplicateCheck { get; set; }
}

I have the real class which has all the properties defined like Value1, Value2 etc, which we will call it as OrderModel

public class OrderModel
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public string Value3 { get; set; }
    public string Value4 { get; set; }
    public string Value5 { get; set; }
}

Now I want to include only those properties for duplicate check which have the respective flag in configuration set to true. Example

bool CheckDuplicate(OrderModel newOrder)
{
OrderModel existingOrder = //GetfromDB;
//Compare only those properties in newOrder and existingOrder which have duplicate check set to true in ConfigurationModel
}

Using reflection to getproperties by string name and then compare is what I had in mind, But wanted to check the best way to do it, keeping performance in mind as well. Any help would be greatly appreciated.

Thanks, AK

1

There are 1 answers

2
Danny Schneider On

When I understand right, the attributes are not known at compile time? In this case I think the best approach is to use the refelction. (By using the nameof() function to get the property from reflection objects, you get a kind of type safety instead of using a harcoded string).

On the otherhand, if you know your full attributes set at compile time, you may create a controlled duplicate check for the attributes, depending on settings in your ConfigurationModel.

EDIT: Simple try a kind of hit test to the database:

bool CheckDuplicate(OrderModel newOrder)
{
  OrderModel existingOrder = //GetfromDB WHERE dbOrder.Value1 == newOrder.Value1 AND dbOrder.Value2 == newOrder.Value2 AND_SO_ON;
  if(existingOrder/*.FirstOrDefault() -> if IEnumerble is returned from DB*/ == null) return false;
  return true;
}