【问题标题】:What are the some data access options for manipulating data using asp.net controls?使用 asp.net 控件操作数据的一些数据访问选项是什么?
【发布时间】:2014-07-30 04:38:41
【问题描述】:

我的第一个问题!

我正在处理的是一个 Webforms 页面,它有很多 ASP 文本框、日期选择器和下拉菜单。现在我正在使用 ADO.net 对所有这些控件进行 CRUD 操作。

我已经非常喜欢这个项目,但我不禁想知道我是否可以以更简单或更有效的方式来做这件事。到目前为止,我对所有内容都使用 SqlDataReader 类。

如果有人可以分解我可用的不同选项或向我指出一些有用的信息,我将不胜感激。我知道这是一个相当广泛的话题。我有点了解 LINQtoSQL 和 EntityFramework。

所以我的问题真的是:ADO.net 与 LINQtoSQL 或 EntityFramework 相比如何?

【问题讨论】:

    标签: asp.net sql vb.net


    【解决方案1】:

    您应该阅读 ADO.NET、Linq 2 SQL 和实体框架中的每个示例并实施它们以了解每个示例的优缺点。一个简单的网络搜索应该会给你样本。

    Linq2Sql 和 EF 将需要您编写非常多的 SQL 查询。一旦你初步掌握了这三件事,在你的代码中遵循这个简单的模式:

    1. 为您的数据访问定义一个接口。
    2. 让您的代码(ascx.cs 和 aspx.cs)与界面一起工作。
    3. 定义基于 ADO.NET、Linq2Sql 或 EF 的接口的具体实现。

    例如

    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)
    

    使用上述方式,您的所有代码都将在接口上运行,如果您决定更改实现,您只需更改一个地方。

    【讨论】:

    • 非常感谢!这正是我正在寻找的。我很高兴能探索这些选项,听起来更干净、更容易。
    猜你喜欢
    • 2011-04-02
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 2013-12-12
    • 2010-09-12
    相关资源
    最近更新 更多