.Net Core how to implement SQLAdapter ./ DataTable function

后端 未结 4 2103
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 04:51

I have a simple .Net Framework routine which runs a query and returns a DataTable object. I need to port this to .Net Core, however I infer that SQLAdapter and DataTable ar

4条回答
  •  遥遥无期
    2020-12-31 05:52

    Instead of DataAdapter/DataTable you may use one of the existing DAL libraries for .NET Core that support CRUD operations over low-level ADO.NET interfaces. Recently I've published NReco.Data: provider-independent DAL that supports automatic SQL statements generation, abstract queries and simple record CRUD operations.

    For example, code snippet from the question can be reimplemented in the following way:

    var con = new SqlConnection(m_ConnectString);
    var dbFactory = new NReco.Data.DbFactory(
        System.Data.SqlClient.SqlClientFactory.Instance);
    var dbCmdBuilder = new NReco.Data.DbCommandBuilder(dbFactory);
    var dbAdapter = new NReco.Data.DbDataAdapter(con, dbCmdBuilder);
    
    var selectRecordsList = dbAdapter.Select( 
        new Query("some_table") ).ToList>();
    

    Complex SQL queries may be executed as application-level data views:

    dbCmdBuilder.Views["some_view"] = new DbDataView(
        @"SELECT @columns FROM Employee emp
          LEFT JOIN Company c ON (c.Id=emp.CompanyId)
          @where[ WHERE {0}] @orderby[ ORDER BY {0}]
        ") {
          FieldMapping = new Dictionary() {
            {"Id", "emp.Id"},
            {"*", "emp.*, c.Title as CompanyTitle"}
          }
        };
    var someViewRS = dbAdapter.Select( new Query("some_view") ).ToRecordSet();
    

    NReco.Data doesn't try to replace SQL with the its own Query (like LINQ does); instead of that it allows you to make simple DB-independent queries from business logic and encapsulate complex SQL syntax with special app-level dataviews that accessed like read-only tables.

    Also it is possible to specify raw SQL query directly with Select method overload (like FromSql in EF Core):

    var userModels = dbAdapter.Select("select * from users where id={0}", 5).ToList();
    

提交回复
热议问题