mercredi 7 février 2018

Retrieve attributes of properties after projection

Considering the following example. It is using entity framework, but I assume that is not really important in this case.

    class Foo
    {
        [CustomAttribute1(Value = "SomeValue")]
        public string Prop { get; set; }

        public Bar Bar { get; set; }
    }

    class Bar
    {
        [CustomAttribute1(Value = "OtherValue")]
        public string Prop { get; set; }
    }

    class CustomAttribute1Attribute : Attribute
    {
        public string Value { get; set; }
    }

and the following code snippet.

    var expr = from f in ctx.Foos
            select new
            {
                Prop1 = f.Prop,
                Prop2 = f.Bar.Prop
            };
    foreach (var obj in expr)
    {
       var attr1 = //retieve "SomeValue" from obj.Prop1
       var attr2 = //retieve "OtherValue" from obj.Prop2
    }

I would like to be able to somehow get those values. I am willing to do some additional actions on expr. I was thinking something like

        var list = WithAttributeProjection(ctx => 
            from f in ctx.Foos
            select new
            {
                Prop1 = f.Prop,
                Prop2 = f.Bar.Prop
            });
        foreach (var obj in list)
        {
            var attr1 = //retieve "SomeValue" from obj.Prop1
            var attr2 = //retieve "OtherValue" from obj.Prop2
        }

        private IEnumerable WithAttributeProjection<T>(Expression<Func<Ctx, T>> expr)
        {                  
           // retrieve destination properties from expr
           // retrieve member expressions               
           // retrieve types from expr
           // retrieve attributes from types
           // create attributes on T [like this][1]   
           foreach (var obj in expr.Compile())
           {
               var result = new T();
               //copy obj to result
               yield return result;
           }                         
        }

But I am open for suggestions.





Aucun commentaire:

Enregistrer un commentaire