Jak tworzyć ogólne metody CRUD Data Access Object (DAO) za pomocą LINQ to SQL

Jestem nowy w LINQ to SQL i próbuję utworzyć ogólny obiekt dostępu do danych (DAO) dla podstawowych metod Create, Read, Update, and Destroy (CRUD), aby móc ponownie użyć kodu. Udało mi się stworzyć metodę generyczną, która usunie dowolny element za pomocą poniższego kodu, ale zastanawiałem się, czy ktoś wie, jak utworzyć metodę generyczną, która wybierze dowolny element za pomocą wspólnego pola Id, które istnieje we wszystkich tabelach.

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

Jestem prawie pewien, że ten sam wzór będzie działał dla update and insert i chciałbym mieć metodę generyczną na GenericDAO, która pobierze mi dowolny podmiot (tj. Klient, Faktura, WorkOrder itp...) na podstawie identyfikatora podmiotu. Z góry dzięki za odpowiedzi.

Author: Mahmoud Gamal, 2012-01-07

1 answers

Myślę, że szukasz wzorca repozytorium , poniżej znajduje się jego prosta implementacja:

Najpierw musisz utworzyć interfejs IRepository w następujący sposób:

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

Potem:

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

Potem:

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

Wtedy możesz mieć coś takiego:

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

Gdzie {[5] } jest encją zmapowaną do twojej bazy danych, która jest zdefiniowana w .dbml. To tylko początek, zobacz poniżej, aby uzyskać więcej szczegółów:

 17
Author: Mahmoud Gamal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:54:22