c# - 通用存储库,CreateObjectSet<T>() 方法

标签 c# asp.net entity-framework asp.net-web-api repository-pattern

我正在尝试实现一个通用存储库,现在我有了这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Entity.Core.Objects;
using Web_API.Models;

namespace Web_API.DAL
{
    class GenericRepository<T> : IRepository<T> where T : class
    {
        private ApplicationDbContext entities = null;
        IObjectSet<T> _objectSet;

        public GenericRepository(ApplicationDbContext _entities)
        {
            entities = _entities;
            _objectSet = entities.CreateObjectSet<T>();
        }

        ...

我在调用此方法时遇到问题: entities.CreateObjectSet<T>(); 应该没问题,但是我收到此错误:

enter image description here

我已经将 System.Data.Entity 添加到我的项目中,此时我不知道还能做什么。我正在学习本教程 http://www.codeproject.com/Articles/770156/Understanding-Repository-and-Unit-of-Work-Pattern .有谁知道如何解决这个问题?

最佳答案

您需要将方法更改为如下所示:

public GenericRepository(ApplicationDbContext _entities)
{
    entities = _entities;
    _objectSet = entities.Set<T>(); //This line changed.
}

这应该具有您想要的功能。 .Set<T>()是返回 DbSet 的通用方法使用的类型。

更新:

随着返回类型的变化,您需要更改您的 _objectSet键入以及。

DbSet<T> _objectSet;

关于c# - 通用存储库,CreateObjectSet<T>() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37240128/

相关文章:

c# - 如何绑定(bind)到通用 Windows 应用程序模板内的空值?

c# - Asp.Net 在 json 中返回自定义对象

c# - 使用 Linq 获取当前和上一个项目

c# - Entity Framework 更新操作 - 为什么首先更新子记录?

c# - Code First with MySQL 不会创建表

c# - 不同命名空间中的 XAML 转换器

c# - 将两个 ASCII 字节打包成一个 ushort

c# - 在 Xamarin.Mac 中使用 SQLite-Net 扩展和 SQLiteConnection

.net - 提供 "hot swap"/在运行时更改程序集的能力,而无需重新启动进程

asp.net - 如何禁用 ASP.NET AJAX ValidatorCalloutExtender 创建的表的填充?