c# - 不在 sportsstore asp.net mvc 5 中实现接口(interface)

标签 c# asp.net asp.net-mvc interface asp.net-mvc-5

我正在关注 apress 的 asp.net mvc 5 书,但我在某一时刻遇到了这个错误:

"SportsStore.Domain.Concrete.EFProductRepository' does not implement interface member 'SportsStore.Domain.Abstract.IProductRepository.Products.set"

这是我在 EFProductRepository 中的内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;

namespace SportsStore.Domain.Concrete
{
    public class EFProductRepository : IProductRepository
    {
        public EFDbContext context = new EFDbContext();

        public IEnumerable<Product> Products
        {
            get { return context.Products; }
        }       
    }
}

在 IProductRepository 中我有:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsStore.Domain.Entities;

namespace SportsStore.Domain.Abstract
{
    public interface IProductRepository
    {
        IEnumerable<Product> Products { get; set; }
    }
}

为什么我在 EFProductRepository.cs 类中收到错误?

最佳答案

因为您没有为属性实现 setter。查看接口(interface)的定义:

IEnumerable<Product> Products { get; set; }

然后看看你的实现:

public IEnumerable<Product> Products
{
    get { return context.Products; }
}

您需要实现 set在属性中,或删除 set从接口(interface)定义。考虑到属性的实现,我猜后者更合适。


如果有帮助,因为看起来您正在为 Entity Framework 对象构建一个存储库,下面是我的一个通常的样子:

public interface ProductRepository
{
    IQueryable<Product> Products { get; }
    void Add(Product model);
    void Remove(Product model);
}

和实现:

public class ProductRepositoryImplementation : ProductRepository
{
    private DbSet<Product> _products;

    public IQueryable<Product> Products
    {
        get { return _products; }
    }

    public ProductRepositoryImplementation(DbSet<Product> products)
    {
        _products = products;
    }

    public void Add(Product model)
    {
        _products.Add(model);
    }

    public void Remove(Product model)
    {
        _products.Remove(model);
    }
}

通常这包含在一个工作对象单元中,它扩展了 DbContext并处理将更改提交到其存储库。 (这也是将 DbSet<> 传递给存储库构造函数的原因。)我实际上是 just blogged。关于今天的设置。

关于c# - 不在 sportsstore asp.net mvc 5 中实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22155523/

相关文章:

c# - EF Core Fluent API 配置防止 TPC 继承

c# - Entity Framework 设置问题

c# - 在不使用查询字符串的情况下在 ASP.NET MVC 应用程序中移动时如何保持 Sharepoint 上下文?

c# - BackgroundWorker 意外死亡

c# - 为什么 .NET 在我的 HTML 中生成 "Span"?

asp.net - 如何在谷歌地图上设置中心?

c# - 在 asp.net core 的每个请求中将用户数据存储在 session 存储中或从数据库中检索?

asp.net-mvc - 如何将布局页面链接到 View MVC 3

ASP.NET MVC : Application_Start and Url. 操作

c# - Miniprofiler 在缺少 CreatedOn 列时中断