How To Create Generic Data Access Object (DAO) CRUD Methods with LINQ to SQL

隐身守侯 提交于 2019-11-28 18:57:15
Mahmoud Gamal

I think you are looking for Repository Pattern, the following is a simple implementation of it:

First you need to create an interface IRepository like this:

public interface IRepository<T> where T : class
{
    void Add(T entity);
    void Delete(T entity);
    void Update(T entity);
    IEnumerable<T> All();
    ...
}

Then:

public class Repository<T> : IRepository<T>
    where T : class, IEntity
{
    DataContext _db;
    public Repository()
    {
        _db = new DataContext("Database string connection");
        _db.DeferredLoadingEnabled = false;
    }
    public void Add(T entity)
    {
        if (!Exists(entity))
            GetTable.InsertOnSubmit(entity);
        else
            Update(entity);
        SaveAll();
    }
    public void Delete(T entity)
    {
        GetTable.DeleteOnSubmit(entity);
        SaveAll();
    }
    public void Update(T entity)
    {
        GetTable.Attach(entity, true);
        SaveAll();
    }
    System.Data.Linq.Table<T> GetTable
    {
        get { return _db.GetTable<T>(); }
    }
    public IEnumerable<T> All()
    {
        return GetTable;
    }
}

Then :

public class CustomerRepository : Repository<Customer>
{
    public ProductRepository()
        : base()
    {
    }
}

Then you can have something like:

Customer newCustomer = new Customer { FistName = "Foo", LastName = "Boo" };
_customerRepository.Add(newCustomer);

Where Customer is an entity mapped to your database which is defined in the .dbml. This is just a start, see the following for more details:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!