简体   繁体   English

Entity Framework 7 创建 DbSet 的内存实现

[英]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.我想创建一个 TestDbSet,它在 EF 7 中提供 DbSet 的内存实现。

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.我在 Add 方法中遇到错误,返回类型必须是EntityEntry<T>以匹配 Overriden Dbset 成员。

I tried to change method signature but I am not sure how to return item as EntityEntry我试图更改方法签名,但我不确定如何将项目作为 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..你能指导我如何在 EF 7 中实现.. 我知道它会在 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.我设法通过返回 null 来覆盖 EF Core 的 Add 方法。 As we are just the data item into list so it doesn't matter if we return null unless you need ChangeTracking Object.由于我们只是列表中的数据项,因此除非您需要 ChangeTracking Object,否则我们是否返回 null 并不重要。

    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>;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM