【问题标题】:Entity Framework with DAL C#带有 DAL C# 的实体框架
【发布时间】:2014-05-26 14:29:03
【问题描述】:

我正在尝试制作发票管理应用程序。

创建 DAL 对象时,我必须为每个表重复 AddDelete 函数。

例如:

public class MyDBProcessor :IMyDBProcessor {
    tpEntities tp=new tpEntities();
    public void AddCustomerToDB(tblCustomers Customer) { tp.tblCustomers.Add(Customer); tp.SaveChanges();}
    public void AddOrderToDB(tblOrders Order) { tp.tblOrders.Add(Order); tp.SaveChanges(); }

    public tblCustomers GetCustomerFromDB(string CustomerID) { return tp.tblCustomers.Where(x => x.ID == CustomerID);   }
    public tblOrders GetOrderFromDB(string OrderID) { return tp.tblOrders.Where(x => x.ID == OrderID); }
}

这很令人沮丧,因为有很多桌子。我想像这样更改 DAL 接口:

public interface IMyGenericDBProcessor {
    void AddToDB<T>(T Record);
    T GetFromDB<T>(int RecordID);
}

所以,当我将数据库引擎 MySQL 更改为 SQL Server 时,反之亦然。如何编写实现IMyGenericDBProcessor 的类?

谢谢,

【问题讨论】:

  • 如果您没有真正的要求来支持多个数据库,那么仅使用抽象来支持多个数据库确实是矫枉过正。在现实世界的应用程序中,您可能只是将每个 DAL 类的内容转换为使用其他数据库引擎。另一方面,如果您想使用抽象来降低复杂性,请提出一个新问题,因为该方法与当前问题不同。至于当前的问题,存储库模式是一种方法:blog.gauffin.org/2013/01/repository-pattern-done-right
  • @jgauffin 你说我需要一个完整的新 DAL 对象?
  • 我不会将所有数据库访问代码放到一个类中。随着应用程序的增长,维护起来会很痛苦。
  • 您正在使用实体框架?在我看来,这已经是一个 DAL。您可能需要数据传输对象来抽象信息,或将其布置在不同的模式中,但如果您正在连接自定义模型 数据库/DAL 层,则不应使用 EF(因为为什么要使用?)
  • 这很好,但是如果您的检查是特定的,那么在通用 DBProc 中编写它们会不会很困难?我的意思是,如果它是通用的,它是——对吗?无论如何,祝你好运:)

标签: c# entity-framework data-access-layer


【解决方案1】:

添加很简单:

public interface IMyGenericDBProcessor
{
    void AddToDB<T>(T Record) where T : class;
}

public class MyDBProcessor : IMyGenericDBProcessor 
{
    public void AddToDB<T>(T record) where T : class
    {
        using(var tp = new tpEntities())
            tp.Set<T>().Add(record);
    }
}

GetFromDb 会更复杂,因为您必须根据实体上下文的元数据确定哪个属性包含 ID,然后基于此构建表达式树。

【讨论】:

  • 完美!对于选择记录,我们可以这样使用: return tp.Database.SqlQuery(T,"select * from " + Fix(TableName) + " where ID='" + Fix(RecordID) + "'");我想不通。 (我们将表名作为字符串,每个表的主键都是 ID)
  • @mustafaöztürk:是的,如果您遵守约定,您可以利用这一点。
猜你喜欢
  • 2013-09-18
  • 2015-11-28
  • 2015-11-29
  • 2022-11-08
  • 1970-01-01
  • 2015-12-26
  • 2012-04-10
  • 2012-09-02
  • 2016-06-22
相关资源
最近更新 更多