【问题标题】:Does not contain a definition or extension method- WHEN IT DOES不包含定义或扩展方法——当它包含
【发布时间】:2014-03-20 10:07:43
【问题描述】:

我已将服务添加到我的 MVC/EF 项目中,以充当我的控制器和存储库之间的层。

我在将方法从存储库复制到服务时遇到问题。我正在尝试在服务中使用Count(),但不断收到错误does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type .. could be found

我的实现方式与存储库完全相同,所以我不知道它为什么会失败

存储库:

public abstract class Repository<CEntity, TEntity> : IRepository<TEntity> where TEntity : class 
                                                                    where CEntity : DbContext, new()
{
    private CEntity entities = new CEntity();
    protected CEntity context
    {
        get { return entities; }
        set { entities = value; }
    }

    public virtual int Count 
    {
        get { return entities.Set<TEntity>().Count(); }
    }

    public virtual IQueryable<TEntity> All()
    {
        return entities.Set<TEntity>().AsQueryable();
    }
}

public interface IRepository<TEntity> : IDisposable where TEntity : class
{
    int Count { get; }
    IQueryable<TEntity> All();
}

服务:

public class CampaignService : ICampaignService 
{
    private readonly IRepository<Campaign> _campaignRepository;

    public CampaignService(IRepository<Campaign> campaignRepository)
    {
        _campaignRepository = campaignRepository;
    }

    public int Count
    {
        get { return _campaignRepository.Count()**; }
    }

    public IQueryable GetAll()
    {
        return _campaignRepository.All();
    }
}

public interface ICampaignService
{
    int Count{ get; }
    IQueryable GetAll();
}

** 它在这一行失败。

`错误 4“MarketingSystem.Repositories.Common.IRepository”不包含“Count”的定义,并且找不到接受“MarketingSystem.Repositories.Common.IRepository”类型的第一个参数的扩展方法“Count”(您是否缺少 using 指令或程序集引用?)

GetAll()/All() 方法可以正常工作,但 Count() 不行。

谁能发现并解释我哪里出错了?

【问题讨论】:

  • 尝试将get { return _campaignRepository.Count()**; } 更改为get { return GetAll().Count(); }

标签: c# asp.net-mvc entity-framework compiler-errors


【解决方案1】:

您正在尝试在存储库上调用 Count()。您的存储库既不是IQueryable&lt;T&gt; 也不是IEnumerable&lt;T&gt;,因此您无法使用扩展方法Count()。实际上,您的存储库仅实现 IRepository&lt;TEntity&gt;,其中只有三个可用成员 - Dispose()CountAll()。我认为您需要从该接口调用Count 属性。

get { return _campaignRepository.Count; }

注意 - Count 不是方法 - 它是属性。

【讨论】:

  • 但是GetAll() 方法工作正常并返回一个可查询的活动选择。之前,我在控制器中调用了_campaignRepository.Count(),它也工作正常。但是服务好像不太喜欢
  • @JakkyD 你可能叫_campaignRepository.All().Count() - 因此All() 返回IQueryable&lt;T&gt; 然后linq 扩展方法Count() 变得可用
  • 谢谢谢尔盖。我把 Count 当作一种方法来对待,而实际上我把它变成了一个我完全忽略的属性!
  • @JakkyD 它经常发生,因为通常你想知道某些集合/序列中的项目数,这里是 Count() 扩展方法 - 很容易弄乱它们:)
【解决方案2】:

删除()

public int Count
{
    get { return _campaignRepository.Count; }
}

Count 是 Repository 中的一个属性,但您将其作为方法访问

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 2015-07-27
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    相关资源
    最近更新 更多