简体   繁体   English

如何将SQL结果转换为C#中的对象列表?

[英]How do I convert SQL results into a list of objects in C#?

I am working on converting a web application over to a WPF desktop application. 我正在将Web应用程序转换为WPF桌面应用程序。 I want to use the existing data access layer so I don't have to rewrite all the SQL queries. 我想使用现有的数据访问层,因此不必重写所有SQL查询。

But, as it stands, everything is populated almost purely from DataTables returned from SQL queries. 但是,就目前而言,所有内容几乎完全是从SQL查询返回的DataTable中填充的。 To make things a bit easier to manage, in some instances, it would really be nice to convert these things into objects. 为了使事情更易于管理,在某些情况下,将这些事情转换为对象确实很不错。

For example, I have a query that pulls out report information. 例如,我有一个查询,可提取报告信息。 I may get 500 results with columns like ReportID, ReportTitle, ReportDate. 使用诸如ReportID,ReportTitle,ReportDate之类的列,我可能会得到500个结果。

I would like to make a report class that has these public attributes and somehow convert the SQL query results into a collection of these report objects. 我想制作一个具有这些公共属性的报表类,并以某种方式将SQL查询结果转换为这些报表对象的集合。

What is the best way to go about doing this? 这样做的最佳方法是什么?

Super bonus points if there is an easy way of going backwards (updating the database if the objects are changed). 如果有简单的后退方法(如果更改了对象,则更新数据库),即可获得超级加分。

You should learn about Object-Relational Mapping (ORM) . 您应该了解对象关系映射 (ORM) A good ORM can save you tonnes of work in the future, and gets those nasty queries out of your code. 一个好的ORM可以在将来节省您大量的工作,并从代码中消除那些讨厌的查询。

I'd recommend NHibernate or Entity Framework 4.0 我建议NHibernateEntity Framework 4.0

While I would also like to suggest ORM (NHibernate is the way to go:)) a possible solution is: 尽管我也想建议ORM(使用NHibernate :),但可能的解决方案是:

public IEnumerable<Report> ToReportList(DataTable dt)
{
  return dt.AsEnumerable().Select(dr => new Report
                                        {
                                            member1 = dr["column1"].ToString(),
                                            ...
                                        });
}

Report is your class here by the way.Such as, 顺便说一句,报告是您的课程。

internal class Report
{
  public string member1{ get; set;}
  ...
}

You may also want to check this, 您可能还需要检查一下,

I think if you search stackoverflow, you will find nicer examples as I remember learning this from here. 我想如果您搜索stackoverflow,您会发现更好的示例,因为我记得从这里学到了这一点。

By the way, if you use NHibernate, you won't have to rewrite your queries at all. 顺便说一句,如果您使用NHibernate,则完全不必重写查询。 All you have to do is map your tables to a class and booya you are good to go. 您所要做的就是将表映射到一个类和booya,这是您的最佳选择。 It will handle all your DML stuff (well mostly) and you can easily tell the ORM to do LazyLoad, Batch processing etc which is pretty cool. 它会处理所有DML内容(大部分情况下),并且您可以轻松地告诉ORM进行LazyLoad,批处理等,这非常酷。

Super bonus points if there is an easy way of going backwards (updating the database if the objects are changed). 如果有简单的后退方法(如果更改了对象,则更新数据库),即可获得超级加分。

For that , go for ORM ie NHibernate (I know I am biased :)). 为此,选择ORM即NHibernate(我知道我有偏见:))。 For LINQ to SQL examples check the 2 links below: 对于LINQ to SQL示例,请查看下面的2个链接:

+1 ORM. +1 ORM。 Entity Framework is good, LINQ to SQL is good too, but you'd need a good database design and is better for pretty basic SQL CRUD actions. 实体框架很好,LINQ to SQL也很好,但是您需要良好的数据库设计,并且对于基本的SQL CRUD操作来说更好。 For custom entities from multiple datasources, I'd go EF. 对于来自多个数据源的自定义实体,我将使用EF。

As far as backwards updating - LINQ to SQL has an easy-peasy implementation, sorta like this - say you've got a db called MyDatabase with Dog entities in it: 至于向后更新-LINQ to SQL有一个简单的实现,有点像这样-假设您有一个名为MyDatabase的数据库,其中包含Dog实体:

using(MyDatabaseDataContext db = new MyDatabaseDataContext())
{
    //LINQ will automatically pluralize your items (entity named Dog becomes Dogs)
    Dog d = db.Dogs.Where(x=>x.DogName.Equals(dogName));
    d.Owner = "Steve";
    db.SubmitChanges();
    //adding new items is easy too
    Dog newdog = new Dog();
    newDog.DogName = "Scruff";
    newDog.Owner = "Jim";
    db.Dogs.Add(newDog);
    db.SubmitChanges();
}

Check out this method. 看看这个方法。 First you can create a class that inherits DataContext. 首先,您可以创建一个继承DataContext的类。 And then you can use methods of DataContext like to ExecuteQuery<> to convert your results in to objects. 然后,您可以使用DataContext的方法(例如ExecuteQuery <>)将结果转换为对象。 With this method you can directly use your queries you wrote earlier. 使用这种方法,您可以直接使用您先前编写的查询。 Also, I feel that this way is a lot better than maintaining a .dbml file, because of the issues associated to synchronization with the actual database schema. 另外,由于与实际数据库模式同步相关的问题,我觉得这种方式比维护.dbml文件要好得多。

Consider the following example. 考虑以下示例。 First you need to define a class for interacting with your database 首先,您需要定义一个用于与数据库交互的类

public class DBManagerDataContext : DataContext
{
    private static string connectionString = ""; // Your connection string

    public static DBManagerDataContext CreateInstance()
    {
        return new DBManagerDataContext(connectionString);
    }

    protected DBManagerDataContext(string connectionString)
        : base(connectionString, new AttributeMappingSource())
    {

    }
}

Then you can use this context to execute queries and convert them in to objects as shown below: 然后,您可以使用此上下文执行查询并将其转换为对象,如下所示:

public class Report
{
    public int ReportID;
    public string ReportTitle;
    public DateTime ReportDate;

    private static string query = "select ReportID, ReportTitle, ReportDate from dbo.Reports"; // Your query

    public static List<Report> GetReportList()
    {
        DBManagerDataContext context = DBManagerDataContext.CreateInstance();
        return context.ExecuteQuery<Report>(query).ToList();
    }
}

You can use the method "GetReportList()" given above like this for example: 您可以像上面这样使用上面给出的方法“ GetReportList()”:

List<Report> reports = Report.GetReportList();

In the case of updates, the method suggested by "jdandison" is a nice option, apart from using the data context as above. 对于更新,“ jdandison”建议的方法是一个不错的选择,除了使用上述数据上下文之外。 In the case of updates it would be "ExecuteCommand" though. 如果是更新,它将为“ ExecuteCommand”。 Please explore the DataContext class for more information. 请浏览DataContext类以获取更多信息。

Edit: Please note that the query column names should match the definition in the object 编辑:请注意查询列名称应与对象中的定义匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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