Querying against DbContext.Set(TypeVariable) in Entity Framework

后端 未结 1 1438
猫巷女王i
猫巷女王i 2020-12-18 05:43

I\'m re-factoring an application to invert some dependencies. Part of the original code uses DbContext.Set() to obtain the set to query agai

相关标签:
1条回答
  • 2020-12-18 06:21

    I haven't compiled it so please excuse any formatting issues - can you use the dynamic type to achieve the same thing?

    private IActionTarget DbContextGetEntity(Type targetType, IActionTarget key)
    {
        dynamic instance = Activator.CreateInstance(targetType);
        return DbContextGetEntity(instance, key);
    }
    
    private IActionTarget DbContextGetEntity<T>(T instance, IActionTarget key)
        where T : class, IActionTarget
    {
        var set = Context.Set<T>(targetType);
        if (set == null)
        {
            throw new Exception();
        }
    
        // Look in the local cache first
        var entity = set.Local
            .FirstOrDefault(l => l.Id == key.Id && l.EffectiveDate == key.EffectiveDate);
    
        if (entity == null)
        {
            // If not found locally, hit the database
            entity = set
                .FirstOrDefault(e => e.Id == key.Id && e.EffectiveDate == key.EffectiveDate);
        }
        return entity;
    }
    
    0 讨论(0)
提交回复
热议问题