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

How To Create Generic Data Access Object (DAO) CRUD Methods with LINQ to SQL(如何使用 LINQ to SQL 创建通用数据访问对象 (DAO) CRUD 方法)
本文介绍了如何使用 LINQ to SQL 创建通用数据访问对象 (DAO) CRUD 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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.

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

我很确定相同的模式将适用于更新和插入,并希望在 GenericDAO 上有一个通用方法,该方法将基于实体 ID.预先感谢您的回复.

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.

推荐答案

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

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

首先你需要像这样创建一个IRepository接口:

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

那么:

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

然后:

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

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

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:

  • 在 LINQ-to-SQL 中实现存储库模式.
  • LINQ to SQL 和存储库模式.
  • 在 LINQ to SQL 中实现 IRepository 模式.
  • Repository Pattern的实现示例在 LINQ to SQL 中.

这篇关于如何使用 LINQ to SQL 创建通用数据访问对象 (DAO) CRUD 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?(Linq to SQL 中是否提供 Unpivot(非 Pivot)功能?如何?)
How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)