vendredi 22 juillet 2016

Dynamically build an object from a strongly typed class using C#?

Currently, am adding the properties and values to the object manually like this example and sending to Dapper.SimpleCRUD to fetch data from Dapper Orm.

object whereCriteria = null;
whereCriteria = new
{
    CountryId = 2,
    CountryName = "Anywhere on Earth",
    CountryCode = "AOE",
    IsActive = true
};

The following class should build the object in the above mentioned format and return the ready-made object.

public static class WhereClauseBuilder
{
    public static object BuildWhereClause(object model)
    {
        object whereObject = null;
        var properties = GetProperties(model);

        foreach (var property in properties)
        {
            var value = GetValue(property, model);

            //Want to whereObject according to the property and value. Need help in this part!!!
        }

        return whereObject;
    }

    private static object GetValue(PropertyInfo property, object model)
    {
        return property.GetValue(model);
    }

    private static IEnumerable<PropertyInfo> GetProperties(object model)
    {
        return model.GetType().GetProperties();
    }
}

This function WhereClauseBuilder.BuildWhereClause(object model) should return the object in expected format (mentiond above). Here is the implementation of how I would like to use.

public sealed class CountryModel
{
    public int CountryId { get; set; }
    public string CountryName { get; set; }
    public string CountryCode { get; set; }
    public bool IsActive { get; set; }
}

public class WhereClauseClass
{
    public WhereClauseClass()
    {
        var model = new CountryModel()
        {
            CountryCode = "AOE",
            CountryId = 2,
            CountryName = "Anywhere on Earth",
            IsActive = true
        };

        //Currently, won't return the correct object because the implementation is missing.
        var whereClauseObject = WhereClauseBuilder.BuildWhereClause(model);
    }
}





Aucun commentaire:

Enregistrer un commentaire