簡體   English   中英

針對基礎實體編程時如何將查詢參數傳遞給實體框架?

[英]How to pass query parameter to entity framework while programming against Base Entity?

在我的項目中,我以前為每個實體都有單獨的存儲庫,但是現在我在利用基礎實體的同時將其重構為一個公共存儲庫。

BaseEntity.cs:

 public abstract class BaseEntity<T> : IEntity<T>
    {
        [NotMapped]
        public abstract T Id { get;  set; }
    }

EFRepository.cs:

 public class EFRepository<TEntity, TId> : IRepository<TEntity, TId> where 
              TEntity : BaseEntity<TId>, new()
    {
        private readonly IDbContext _context;
        private DbSet<TEntity> _entities;

        public EFRepository(IDbContext context)
        {
            _context = context;
        }

        private DbSet<TEntity> Entities
        {
            get { return _entities ?? (_entities = _context.Set<TEntity>()); }
        }

        public async Task<TEntity> GetByIdAsync(TId id)
        {
            return await Entities.FindAsync(id);
        }

        public void Insert(TEntity entity)
        {
            Entities.Add(entity);
            _context.SaveChanges();
        }

        public async Task UpdateAsync(TEntity entity)
        {
            await _context.SaveChangesAsync();
        }

        public void Delete(TId id)
        {
            var entity = new TEntity
            {
                Id = id
            };

            // Attach the entity to the context and call the delete method.
            Entities.Attach(entity);
            Delete(entity);
        }

        public void Delete(TEntity entity)
        {
            Entities.Remove(entity);
            _context.SaveChanges();
        }

        public IList<TEntity> Table
        {
            get { return Entities.ToList(); }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_context != null)
                {
                    _context.Dispose();
                }
            }
        }

上面的實現在大多數情況下都是完美的,但是在這種情況下,我有一個客戶實體,並且該客戶實體包含字段SearchTerms因此如果我必須基於SearchTerms執行過濾器,則無法使用以上方法。 我也不想在基本實體中添加該字段,因為它僅針對客戶實體。 關於如何根據SearchTerms過濾結果的任何幫助嗎?

創建一個單獨的CustomerRepository類,並實現您自己的過濾器邏輯,如下所示。

public class CustomerRepository : EFRepository<Customer, Guid>, ICustomerRepository
{
    public CustomerRepository(IDbContext context): base(context) {}

    public async Task<List<Customer>> GetCustomerBySearchTerms(string[] searchTerms)
    {
       //implement your logic here
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM