开发者

How to move from untyped DataSets to POCO\LINQ2SQL in legacy application

Good day!

I've a legacy application where data access layer consists of classes where queries are done using SqlConnection/SqlCommand and results are passed to upper layers wrapped in untyped DataSets/DataTable.

Now I'm working on integrating this application into newer one where written in ASP.NET MVC 2 where LINQ2SQL is used for data access. I don't want to rewrite fancy logic of generating complex queries that are passed to SqlConnection/SqlCommand in LINQ2SQL (and don't have permission to do this), but I'd like t开发者_开发问答o have result of these queries as strong-typed objects collection instead of untyped DataSets/DataTable.

The basic idea is to wrap old data access code in a nice-looking from ASP.NET MVC "Model".

What is the fast\easy way of doing this?

Additionally to the answer below here is a nice solution based on AutoMapper: http://elegantcode.com/2009/10/16/mapping-from-idatareaderidatarecord-with-automapper/


An approach that you could take is using the DataReader and transfer. So for every object you want to work with define the class in a data transfer object folder (or however your project is structured) then in you data access layer have something along the lines of the below.

We used something very similar to this in a project with a highly normalized database but in the code we did not need that normalization so we used procedures to put the data into more usable objects. If you need to be able to save these objects as well you will need handle translating the objects into database commands.

What is the fast\easy way of doing this?

Depending on the number of classes etc this is could not be the fastest approach but it will allow you to use the objects very similarly to the Linq objects and depending on the type of collections used (IList, IEnumerable etc) you will be able to use the extension methods on those types of collections.

public IList<NewClass> LoadNewClasses(string abc)
{
    List<NewClass> newClasses = new List<NewClass>();

    using (DbCommand command = /* Get the command */)
    {
        // Add parameters
        command.Parameters["@Abc"].Value = abc;

        // Could also put the DataReader in a  using block
        IDataReader reader = /* Get Data Reader*/;

        while (reader.Read())
        {
            NewClass newClass = new NewClass();
            newClass.Id = (byte)reader["Id"];
            newClass.Name = (string)reader["Name"];

            newClasses.Add(newClass);
        }

        reader.Close();
    }

    return newClasses;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜