Home > Mobile >  Entity Framework Core can't infer type from generic
Entity Framework Core can't infer type from generic

Time:04-19

I have been trying to implement a generic repository and I have found that Entity Framework Core can't infer types from generics and I think I might forced to do extension method with typed entities, is it not possible to use generics on Join with Linq?

public  async Task<IEnumerable<V>> Join<V, T, VID, TID>(this EntityRepository<T> repositoryEntity,
        Func<T, TID> joinIdEntity, Func<V, VID> joinIdEntity1,Func<V, T, V> join)
            where T : class, new()
            where V : class, new()
    {
        Db.Set<T>()
          .Join(Db.Set<V>(), joinIdEntity, joinIdEntity1, join);
    }

CodePudding user response:

You could use virtual props in your model so you don't have to use join EF Core will get everything for you if you set correctly your model with annotations

CodePudding user response:

I believe it was conflicting with the T entity generic on the class so the correct way to write it would be

 public async Task<ICollection<TResult>> Join<VEntity, TKey, TResult>(Expression<Func<T, TKey>> outerKeySelector, Expression<Func<VEntity, TKey>> innerKeySelector, Expression<Func<T, VEntity, TResult>> resultSelector) 

        where VEntity : class ,new()
        where TResult : class,new()
    {
        try
        {
            return await Db.Set<T>().Join(Db.Set<VEntity>(), outerKeySelector, innerKeySelector, resultSelector).ToListAsync(); ;

        }
        catch (Exception ex)
        {
            return null;
        }
    }

CodePudding user response:

The issue is the VID and TID generic parameter. According the Join method signature the join key must be of the same type. Since joinIdEntity is of type Func<T,TID> joinIdEntity and JoinIdEntity1 is of type Func<V, VID> no join is possible. The only solution is to declare the method as following:

public  async Task<IEnumerable<V>> Join<V, T,VID>(this EntityRepository<T> repositoryEntity,Expression<Func<T,VID>> joinIdEntity, Expression<Func<V, VID>> joinIdEntity1,Func<V,T,V> join)
        where T : class, new()
        where V : class, new()
    {

        return Db.Set<T>().Join(Db.Set<V>(), joinIdEntity, joinIdEntity1, (e,v) => v);
    }
  • Related