views:

107

answers:

2

I've a table like this :

ID  Name  Key  Value
1   Mydata1  Mail  myval1
1   Mydata1  Name  myval2
1   Mydata1  Nick  myval3
1   Yourdata key2  myval4

and a class like this :

[Serializable]
public class Mydata
{
    public string Mail{get;set;}
    public string Name{get;set;}
    public string Nick{get;set;}
}

I extract from my Table data where Name = 'MyData1' in a list.

How To serialize this data in my class. Thanks!

+1  A: 

You should look into LINQ to SQL, LINQ to Entities, NHibernate, etc. These are OR Mappers, or Object/Relational Mappers. They are designed to query your database for you, and return serialized objects from your domain. They can greatly reduce the amount of effort it takes to build an application with objects that are persisted to and retrieved from a database server.

Note that Linq to SQL required SQL Server, while the other two can be used with any database.

jrista
I don't think any of those will *directly* do the translation required here...
Marc Gravell
A: 

If you have your class already, you are looking for "POCO" support in an ORM.

E.g. Entities Framework v4 does this. See here for details. I understand nHibernate has this support today.

Alternatively in your data access layer, you can do the conversion in your data access layer (DTO == Data Transfer Object) using a data reader:

var rs = dbCmd.ExecuteReader();
var results = new List<MyDto>();
while (rs.Read()) {
  results.Add(new MyDto {
    Id = rs.ReadInt("Id"),
    Name = rs.ReadString("Name"),
    ...
  };
}

Using LINQ to SQL:

using (var dc = MyDataContext()) {
  var results = from d in dc.MyDataType
                select new MyDto {
                  Id = d.Id,
                  Name = d.Name,
                  ...
                };
}

However I tend to add a method to customise the generated entity with a helper method to perform the mapping (which helps avoid repeating the property copy code for each query).

Richard