简体   繁体   中英

Error on implementing generic Repository for CRUD operations using Entity Framework

I have a problem, I want to get table from my generic class:

public virtual TEntity GetById(int id)
{
    return _db.Set<TEntity>().FirstOrDefault(c => ((IEntity)c).Code == id);
}

But Linq can't cast IEntity

public abstract class BaseRepository<TEntity, M> : IRepository<TEntity> where TEntity : class where M : new()

If a replace TEntity : class with TEntity : IEntity I get this error :

The type 'TEntity' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Entity.DbContext.Set()'

You need to specify two generic constraints, what you already have ( class ) to specify the type argument must be a reference type, and an interface constraint to specify that TEntity must implement your IEntity interface:

                                                                                               ^^here^^
public abstract class BaseRepository<TEntity, M> : IRepository<TEntity> where TEntity : class, IEntity where M : new()

After that you should be able to do this:

public virtual TEntity GetById(int id)
{
   return _db.Set<TEntity>().FirstOrDefault(c => c.Code == id);
}

But anyway I want to suggest if you're creating a generic repository, your GetById method should be "more flexible", for example you could do the following:

public virtual TEntity Find(params object[] keyValues)
{
   return _db.Set<TEntity>().Find(keyValues);
}

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