简体   繁体   中英

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.

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:

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. How can I write a class that implemets 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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