首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取类的所需属性

获取类的所需属性
EN

Stack Overflow用户
提问于 2018-10-11 21:05:52
回答 1查看 125关注 0票数 2

我有大约15个实体,我必须为它们获取idname属性。首先,我检查是否可以从本地缓存中提取属性。如果不是,那么我通过代码从DB中获取它们,并保存在缓存中。

下面是我的两个实体的代码:

public class GetParamsService : IGetParamsService
{
    private readonly IMemoryCache _cache;
    private readonly MemoryCacheEntryOptions _cacheOptions;
    private readonly IDealTypeRepository _dealTypeRepository;
    private readonly ICurrencyRepository _currencyRepository;      

    public GetParamsService(IMemoryCache memoryCache, 
        IDealTypeRepository dealTypeRepository,
        ICurrencyRepository currencyRepository)
    {
        _cache = memoryCache;
        _cacheOptions = new MemoryCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromHours(2));

        _dealTypeRepository = dealTypeRepository;
        _currencyRepository = currencyRepository;
    }

    public async Task<(int idDealType, string dealTypeName)> GetDealTypeParams(
        string dealTypeCode)
    {
        if (!_cache.TryGetValue(CacheKeys.IdDealType, out int idDealType)
            | !_cache.TryGetValue(CacheKeys.DealTypeName, out string dealTypeName))
        {
            var dealType = await _dealTypeRepository
                .Get(x => x.Code == dealTypeCode, dealTypeCode);

            idDealType = dealType.IdDealType;
            dealTypeName = dealType.Name;

            _cache.Set(CacheKeys.IdDealType, idDealType, _cacheOptions);
            _cache.Set(CacheKeys.DealTypeName, dealTypeName, _cacheOptions);
        }

        return (idDealType, dealTypeName);
    }

    public async Task<(int idCurrency, string currencyName)> GetCurrencyParams(
        string currencyCode)
    {
        if (!_cache.TryGetValue(CacheKeys.IdCurrency, out int idCurrency)
            | !_cache.TryGetValue(CacheKeys.CurrencyName, out string currencyName))
        {
            var currency = await _currencyRepository
                .Get(x => x.Code == currencyCode, currencyCode);

            idCurrency = currency.IdCurrency;
            currencyName = currency.Name;

            _cache.Set(CacheKeys.IdCurrency, idCurrency, _cacheOptions);
            _cache.Set(CacheKeys.CurrencyName, currencyName, _cacheOptions);
        }

        return (idCurrency, currencyName);
    }
}

因此,GetDealTypeParamsGetCurrencyParams方法基本相同,我想创建一个泛型方法,而不是许多相似的方法。我想这是有道理的。

问题是我不知道如何在CacheKeys类中获得“给定实体的正确属性”:

public static class CacheKeys
{
    public static string IdDealType => "_IdDealType";

    public static string DealTypeName => "_DealTypeName";

    public static string IdCurrency => "_IdCurrency";

    public static string CurrencyName => "_CurrencyName";

    // ...

}

每个存储库都是通过Get方法从GenericRepository继承的:

public class DealTypeRepository : GenericRepository<DealTypeEntity>, IDealTypeRepository
{       
    public DealTypeRepository(DbContextOptions<MyContext> dbContextOptions)
        : base(dbContextOptions)
    {

    }
}

public class GenericRepository<TEntity> where TEntity : class
{
    private readonly DbContextOptions<MyContext> _dbContextOptions;

    public GenericRepository(DbContextOptions<MyContext> dbContextOptions)
    {
        _dbContextOptions = dbContextOptions;
    }

    public async Task<TEntity> Get(Expression<Func<TEntity, bool>> predicate, string code)
    {
        try
        {
            using (var db = new MyContext(_dbContextOptions))
            {
                using (var tr = db.Database.BeginTransaction(
                    IsolationLevel.ReadUncommitted))
                {
                    var entity = await db.Set<TEntity>().AsNoTracking()
                        .FirstAsync(predicate);

                    tr.Commit();

                    return entity;
                }
            }
        }
        catch (Exception e)
        {
            throw new Exception("Error on getting entity by code: {code}");
        }
    }
}

您能指导我如何检索CacheKeys类的所需属性来编写泛型方法吗?我想这可以通过反射很容易完成。

更新:我不确定是否必须尝试一个泛型方法,因为每个实体都有自己名称的Id属性(例如,IdDealType代表dealType,IdCurrency代表货币)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-11 22:30:23

在我开始之前:这个解决方案假设您的所有实体都遵循您在示例代码中显示的命名约定。

首先,如果您有一个专用于此服务的存储库,这样就可以按任何实体类型进行查询,这会更好。在那里,您将使用您的约定来获取这些属性名称,并且可以使用EF.Property来查询它们。由于您的所有查询似乎都在Code列上,因此我们还可以简化该repo方法上的参数。

public class ParamRepository : IParamRepository
{
    private readonly DbContextOptions<MyContext> _dbContextOptions;

    public ParamRepository(DbContextOptions<MyContext> dbContextOptions)
    {
        _dbContextOptions = dbContextOptions;
    }

    public async Task<(int id, string name)> GetParamsByCode<TEntity>(string code) where TEntity : class
    {
        string entityName = typeof(TEntity).Name;
        string idProp = $"Id{entityName}";
        string nameProp = $"{entityName}Name";
        try
        {
            using (var db = new MyContext(_dbContextOptions))
            {
              var entity = await db.Set<TEntity>().AsNoTracking()
                        .Where(p => EF.Property<string>(p, "Code") == code)
                        .Select(p => new { Id = EF.Property<int>(p, idProp), Name = EF.Property<string>(p, nameProp)})
                        .FirstAsync();

              return (id: entity.Id, name: entity.Name);
            }
        }
        catch (Exception e)
        {
            throw new Exception("Error on getting entity by code: {code}");
        }
    }
}

您还需要重构您的缓存键以根据约定创建:

public static class CacheKeys
{
    public static string GetIdKey<TEntity>() => $"_Id{typeof(TEntity).Name}";
    public static string GetNameKey<TEntity>() => $"_{typeof(TEntity).Name}Name";
}

然后,在GetParamsService上变得很容易:

public class GetParamsService
{
    private readonly IMemoryCache _cache;
    private readonly MemoryCacheEntryOptions _cacheOptions;
    private readonly IParamRepository _paramRepository;

    public GetParamsService(IMemoryCache memoryCache,
        IParamRepository paramRepository)
    {
        _cache = memoryCache;
        _cacheOptions = new MemoryCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromHours(2));

        _paramRepository = paramRepository;
    }

    public async Task<(int id, string name)> GetParams<TEntity>(string code) where TEntity : class
    {
        string cacheIdKey = CacheKeys.GetIdKey<TEntity>();
        string cacheNameKey = CacheKeys.GetNameKey<TEntity>();
        if (!_cache.TryGetValue(cacheIdKey, out int cacheId)
            | !_cache.TryGetValue(cacheNameKey, out string cacheName))
        {
            var param = await _paramRepository.GetParamsByCode<TEntity>(code);

            cacheId = param.id;
            cacheName = param.name;

            _cache.Set(cacheIdKey, cacheId, _cacheOptions);
            _cache.Set(cacheNameKey, cacheName, _cacheOptions);
        }

        return (cacheId, cacheName);
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52760820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档