简体   繁体   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
    }

In the above line of code, I don't understand why I am not getting Count property. 在上面的代码行中,我不明白为什么我没有获得Count属性。 Instead I get CountAsynch. 相反,我得到了CountAsynch。 I really want to simply get Count property. 我真的很想简单地获取Count属性。 My IQueryable for FindAll is correctly defined in the interface and in the class method. 我的IQueryable for FindAll在接口和类方法中正确定义。

You may have forgotten to include the right namespace. 您可能已经忘记了包含正确的名称空间。

The method you're seeing in IntelliSense is named QueryableExtensions.CountAsync<TSource> defined in the System.Data.Entity namespace, which returns Task<int> and, as such, should be awaited. 您在IntelliSense中看到的方法名为System.Data.Entity命名空间中定义的QueryableExtensions.CountAsync<TSource> ,它返回Task<int> ,因此应等待。

The method (not property ) you're looking for is named Queryable.Count<T>() and is defined in the System.Linq namespace. 您要查找的方法 (不是property )名为Queryable.Count<T>()并且在System.Linq命名空间中定义。 It returns an int and should not be awaited. 它返回一个int ,不应等待。

If the operation involves IO, which it probably does, you want to use CountAsync . 如果操作可能涉及IO, CountAsync使用CountAsync

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

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