开发者

How do I make a Generic Data Access Class?

ASP.net C# 3.5 Framework, working in Visual Studio 2008 currently.

What I want is a Generic Data Access Class. I have seen several of them but what I want is to see one that I pass the Co开发者_如何转开发nnection String and the SQL statement and it will return a List of Objects or when only one item an Object or when no response needed a boolean to let me know if it succeeded?

I hope this makes sense if not let me know and I will explain more.


You don't have to roll your own. Check out Microsoft.Data.dll. It's somewhere in between the low level ADO.NET code (using SqlConnection, SqlCommand, etc.) and a higher level ORM framework like LINQ to SQL or nHibernate:

Introduction to Microsoft.Data.dll

Then your access becomes as easy as:

var db = Database.OpenConnectionString(connString);
for(var user in db.Query("select * from users"))
{
    var username = user.Username;
    // Do other stuff here
}


Have you looked at LINQ-to-SQL (wouldn't recommend this though, it's not going to get much attention from Microsoft in the future), LINQ-to-Entities (this is what Microsoft is dedicating resources to in this area for the foreseeable future), NHibernate, or any other ORM(-ish) libraries for .NET?

Any of them will have mechanisms to allow you to create your queries (in a more typesafe way, I might add) and get the results back in an object form (or get results from procedures if you are dealing with scalar results).

Now, it is the case that it doesn't allow you to pass the query string, but if you are dynamically generating this, then more often than not, that's a really bad thing, as most composed dynamic SQL statements, if not using parameters (which you aren't indicating you are) are subject to SQL injection attacks.

When using any of the libraries above, you can compose your query, and the parameters will be parsed and the dynamic sql under the covers will be generated safely, not subject to SQL injection attacks.


Check out my answer to this question:

Fastest method for SQL Server inserts, updates, selects

It's not a complete class, but it lays out the groundwork for a nice generic implementation that will work with linq-to-objects.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜