C# 如何使用 LINQ to SQL 创建通用数据访问对象 (DAO) CRUD 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8766794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:21:40  来源:igfitidea点击:

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

c#linqlinq-to-sqlcruddao

提问by Grasshopper

I am new to LINQ to SQL and attempting to create a generic Data Access Object (DAO) for the basic Create, Read, Update, and Destroy (CRUD) methods so that I can reuse the code. I was successful in creating a generic method that will delete any entity by using the code below but, I was wondering if anyone knows how to create a generic method that will select any entity by a common Id field that exists on all tables.

我是 LINQ to SQL 的新手,并试图为基本的创建、读取、更新和销毁 (CRUD) 方法创建通用数据访问对象 (DAO),以便我可以重用代码。我成功地创建了一个通用方法,该方法将使用下面的代码删除任何实体,但是,我想知道是否有人知道如何创建一个通用方法,该方法将通过所有表上存在的公共 Id 字段选择任何实体。

    /// <summary>
    /// Generic method that deletes an entity of any type using LINQ
    /// </summary>
    /// <param name="entity"></param>
    /// <returns>bool indicating whether or not operation was successful</returns>
    public bool deleteEntity(Object entity)
    {
        try
        {
            DomainClassesDataContext db = new DomainClassesDataContext();
            db.GetTable(entity.GetType()).Attach(entity);
            db.GetTable(entity.GetType()).DeleteOnSubmit(entity);
            db.SubmitChanges();
            return true;
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.StackTrace);
            return false;
        }
    }

I am pretty sure that the same patter will work for update and insert and would like to have a generic method on the GenericDAO that will retrieve me any entity (i.e. Customer, Invoice, WorkOrder, etc...) based on the entities Id. Thanks in advance for the replies.

我很确定相同的模式将适用于更新和插入,并希望在 GenericDAO 上有一个通用方法,该方法将根据实体 Id 检索任何实体(即客户、发票、工作订单等)。预先感谢您的答复。

采纳答案by Mahmoud Gamal

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

我认为您正在寻找Repository Pattern,以下是它的一个简单实现:

First you need to create an interface IRepositorylike this:

首先你需要创建一个IRepository这样的界面:

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 Customeris an entity mapped to your database which is defined in the .dbml. This is just a start, see the following for more details:

Customer映射到您的数据库的实体在哪里,该实体在.dbml. 这只是一个开始,有关更多详细信息,请参阅以下内容: