Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing an n number of objects in one object

In an sql statement the result of join returns multiple modeled objects, i thought of a way to model them and came up with

 class JoinObjectsMapper
    {
        //add 2 fields one for the PK value and one for the name of the PK


        internal readonly Dictionary<Type, object> Objs;

        public JoinObjectsMapper(params object[]  objs)
        {
            Objs = new Dictionary<Type, object>();
            foreach(var o in objs)
            {
                Objs[o.GetType()] = o;
            }
        }

        public object this[Type key]
        {
            get { return Objs[key]; }
            set { Objs[key] = key; }
        }

    }

example usage:

 var custmer = new Customer { customer_id = 1, customer_name = "zxc" };
 var order = new Order { order_id = 1, customer_id = 1, order_amount = 200.30m };
 var mapper = new JoinObjectsMapper(custmer, order);
 var cus = mapper[typeof(Customer)] as Customer;
 var order = mapper[typeof(Order)] as Order;

which is working except i don't like the fact that i have to cast the object after retrieving it, and if i use generics then it won't work for n number of objects except if i write so many overloads as far as i know.

any idea how to retrieve my objects as

 var cus = mapper[typeof(Customer)];
 var order = mapper[typeof(Order)];

Or

 var cus = mapper.Ref<Customer>();
 var order = mapper.Ref<Order>();

and still get the right types and avoid casting?

like image 545
user1492051 Avatar asked Nov 22 '25 13:11

user1492051


2 Answers

If you just don't like having to perform the cast external of the JoinObjectsMapper you can add the cast to the JoinObjectsMapper definition:

public T Ref<T>(){
    return (T)Objs[typeof(T)];
}
like image 143
James Avatar answered Nov 24 '25 02:11

James


Another thing to notice to catch exception.

public T Ref<T>(){
    if (!(Objs[typeof(T)] is T)
        throw new InvalidCastException();

    return (T)Objs[typeof(T)];
}
like image 31
Turbot Avatar answered Nov 24 '25 02:11

Turbot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!