简体   繁体   English

使用DAL C#的实体框架

[英]Entity Framework with DAL C#

I am trying to make an invoice managing application. 我正在尝试制作发票管理应用程序。

When creating DAL object, I have to repeat Add and Delete functions for every table. 创建DAL对象时,我必须为每个表重复AddDelete功能。

For example: 例如:

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); }
}

It is very frustrating because there are so many tables. 这非常令人沮丧,因为表太多了。 I want to change DAL interface like this: 我想这样更改DAL接口:

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

So, when I change db engine MySQL to SQL Server or vice versa. 因此,当我将数据库引擎MySQL更改为SQL Server时,反之亦然。 How can I write a class that implemets IMyGenericDBProcessor ? 如何编写实现IMyGenericDBProcessor的类?

Thank you, 谢谢,

Adding is easy: 添加很容易:

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 would be more complicated because you'd have to determine, based on the entity context's metadata, which property comprises the ID, and then construct an expression tree based on that. GetFromDb会更加复杂,因为您必须基于实体上下文的元数据确定哪个属性包含ID,然后基于该ID构造一个表达式树。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM