繁体   English   中英

IQueryable不返回Count属性

[英]IQueryable does not return Count property

    public interface IRepository<T> : IDisposable
    {
        void Add(T newEntity);
        void Delete(T entity);
        T Find(int id);
        IQueryable<T> FindAll();
        int Commit();
    }

  public class SqlRepository<T> : IRepository<T> where T : class
    {
        DbContext context;
        DbSet<T> set;
        public SqlRepository(DbContext context)
        {
            this.context = context;
            this.set = context.Set<T>();
        }

        public void Add(T newEntity)
        {
            this.set.Add(newEntity);
        }

        public void Delete(T entity)
        {

        }

        public T Find(int id)
        {
            throw new Exception("todo");
        }

        public IQueryable<T> FindAll()
        {
            return this.set;
        }

        public int Commit()
        {
            return this.context.SaveChanges();
        }

        public void Dispose()
        {
            this.context.Dispose();
        }
    }


    using (IRepository<Contact> e = new SqlRepository<Contact>(new AppointmentReminderDb()))
    {
        e.Add(new Contact() { Active = true });
        e.Add(new Contact() { Active = true });
        e.Commit();
        var count = await e.FindAll().Count(); // do not get Count property
    }

在上面的代码行中,我不明白为什么我没有获得Count属性。 相反,我得到了CountAsynch。 我真的很想简单地获取Count属性。 我的IQueryable for FindAll在接口和类方法中正确定义。

您可能已经忘记了包含正确的名称空间。

您在IntelliSense中看到的方法名为System.Data.Entity命名空间中定义的QueryableExtensions.CountAsync<TSource> ,它返回Task<int> ,因此应等待。

您要查找的方法 (不是property )名为Queryable.Count<T>()并且在System.Linq命名空间中定义。 它返回一个int ,不应等待。

如果操作可能涉及IO, CountAsync使用CountAsync

暂无
暂无

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

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