CrazyPaste CrazyPaste - 4 months ago 12
SQL Question

What are the some data access options for manipulating data using asp.net controls?

My first question on SO!

What I'm working on is a Webforms page that's has a lot ASP textboxes, datepickers and dropdowns. Right now I'm using ADO.net for all of these controls to do CRUD operations.

I'm already a great deal into this project, but I can't help wondering if I could be doing this in an easier or more efficient way. So far I'm using the SqlDataReader class for everything.

If someone could break down the different options available to me or point me to some good information, I'd appreciate it. I know it's a pretty broad topic. I'm kind of aware of LINQtoSQL and EntityFramework.

So my question really is: How does ADO.net compare to LINQtoSQL or EntityFramework?

Answer

you should read up on one sample each of ADO.NET, Linq 2 SQL and Entity Framework and implement them to know the pros/cons of each. a simple web search should give you samples.

Linq2Sql and EF will require very SQL query writing from you. once you have an initial grasp of these 3 things individually, follow this simple pattern in your code:

  1. define an interface for your data access.
  2. let your code behind (ascx.cs and aspx.cs) work with the interface.
  3. define concrete implementations of the interface based on ADO.NET, Linq2Sql or EF.

e.g.

public interface IRepository
{
 MyDto GetData(int id);
 // and so on
}

public class EntityFrameworkRepository : IRepository
{
 public MyDto GetData(int id)
 {
  using (var db = new MyDbContext())
  {
   var myDtoEntity = db.MyDtoEntity.FirstOrDefault(m => m.Id == id);

   // extension method to transform DB objects into DTOs
   return myDtoEntity.ToMyDto(); 
  }
 }
}

// similarly you can do:

public class Linq2SqlRepository : IRepository
{
 // so on..
}

// now for all your aspx.cs pages: derive them from a base page, 
// and in the base page
// have a variable like this, so that all pages have access to this.

public IRepository Repository {get; set;}

// you can have static instances as well for one time initialization.

// you can initialize the Repository with a particular concrete implementation
// or inject it. (if you're well versed with Dependency Injection)

using the above way, all your code will work off the Interface, and you just need to change one place if you decide to change the implementation.

Comments