开发者

How do I map similar linq2sql generated results to a single object?

I am trying to refactor some methods to avoid repeating myself in the object mappings. The functions are laid out in this SO question.

I have a generic method that will call one of 4 stored procedures, that return results with the same fields, just different subsets of data. linq2sql generates a different Result object for each stored procedure.

Is there a way to map the results to my server object generically? Does it require re开发者_如何学JAVAflection?

private static List<DistroHeader> getHeaders<T>(Func<IEnumerable<T>> getHeaders)
{
    List<MyObj> myObj = new List<MyObj>();

    var result = from a in getMyObjData()
                 select a;

    foreach (var row in result)
        {
            myObj.Add(new MyObj()
            {
                Id = row.id,
                Description = row.descr,
                // ...etc
                // These fields are shared across the result types...
                // is there a way to make the compiler recognize that?
            });
        }
}


The linq would be something like the following:

     var result = from a in getMyObjData()
                  select new { Id = a.id, Description = a.description };

A good resource for linq is 101 Linq Samples.


EDIT:
It depends on what your needs are. The above is a really simple example of creating a generic object.

A better answer to your question would have been what you can see below because it is actually creating the object of the type that you need.

 MyObject newOject = from item in getMyObjData()
                     select new MyObject() 
                            {
                                 Id = item.Id, 
                                 Description = item.description 
                            };


I'd look into using AutoMapper.


I'm guessing this isn't good practice, but this is what I did:

private static List<DistroHeader> getHeaders<T>(Func<IEnumerable<T>> getHeaders)
{
    List<MyObj> myObj = new List<MyObj>();

    var result = from a in getMyObjData()
                 select a;

    var pi = new List<PropertyInfo>(typeof(T).GetProperties());

    foreach (var row in result)
    {
        myObj.Add(new MyObj()
        {
            Id = (int)pi.Find(x => x.Name == "id").GetValue(row, null),
            Description = (string)pi.Find(x => x.Name == "descr").GetValue(row, null),
            // ...etc      
        });
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜