简体   繁体   中英

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 reflection?

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      
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM