简体   繁体   中英

LINQ to SQL: Check for existence of a generic entity in a generic Repository

I have a generic repository as like that

public class Repository<T> : IRepository<T> where T: class
{
    DataContext _db;
    public Repository()
    {
        _db = new DataContext("connection string");
    }
    System.Data.Linq.Table<T> GetTable
    {
        get { return _db.GetTable<T>(); }
    }
    public T GetBy(Func<T, bool> exp)
    {
        return GetTable.SingleOrDefault(exp);
    }
    ....
}

Is it possible to add a generic method to this repository to check for the existence of any entity like that:

public bool IsExisted(T entity)
{
    ...
}

it is easy to write it in any repository

_productRepository.GetBy(p => p.Id == 5 // or whatever);

where the productRepository like this:

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

I came to this since i always want to check for the existence of an entity alot, so i don't need to write the same method in all repositories.

If all your entities have for example a property Guid Id you can create the following interface for your entities:

public interface IEntity
{
    Guid Id { get; set; }
}

And restrict your Repository class to it:

public class Repository<T> : IRepository<T>
    where T : class, IEntity
{
   ....
}

You can then define the following function in your base repository:

public bool Exists(T entity)
{
    return GetTable.Any(e => e.Id == entity.Id);
}

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