简体   繁体   中英

Entity Framework 7 Create in-memory implementation of DbSet

Sorry I am new to Entity Framework..

I want to created a TestDbSet that provides an in-memory implementation of DbSet in EF 7.

public class TestDbSet<TEntity> : DbSet<TEntity>, IQueryable, IEnumerable<TEntity>, IDbAsyncEnumerable<TEntity> 
        where TEntity : class 
    { 
        ObservableCollection<TEntity> _data; 
        IQueryable _query; 


    public TestDbSet() 
    { 
        _data = new ObservableCollection<TEntity>(); 
        _query = _data.AsQueryable(); 
    } 

    public override TEntity Add(TEntity item) 
    { 
        _data.Add(item); 
        return item; 
    } 

    public override TEntity Remove(TEntity item) 
    { 
        _data.Remove(item); 
        return item; 
        } 
 }

I am getting error in Add method that return type must be EntityEntry<T> to match Overriden Dbset member.

I tried to change method signature but I am not sure how to return item as EntityEntry

 public override EntityEntry<T> Add(T item) 
        {
           _data.Add(item);
            return  item;
        }

I could not find similar issue. Can you guide me how we implement in EF 7.. I know it will work in EF 6..

对于没有真实数据库的测试,您可以使用 Microsoft.EntityFrameworkCore.InMemory

Sorry I know this is very old thread. But thought if this helps. I managed to override the Add method for EF Core by returning null. As we are just the data item into list so it doesn't matter if we return null unless you need ChangeTracking Object.

    public override EntityEntry<T> Add(T item)
    {
        _data.Add(item);

        return null;
    }

I solved it by the following code

 public override EntityEntry<T> Add(T item) 
 {
           _data.Add(item);
            return item as EntityEntry<T>;
 }

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