【问题标题】:Generic Repository, CreateObjectSet<T>() Method通用存储库,CreateObjectSet<T>() 方法
【发布时间】:2016-09-11 10:17:41
【问题描述】:

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

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&lt;T&gt;(); 应该没问题,但是我收到此错误:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    这应该有你想要的功能。 .Set&lt;T&gt;() 是返回所用类型的DbSet 的泛型方法。

    更新:

    随着返回类型的更改,您还需要更改 _objectSet 类型。

    DbSet<T> _objectSet;
    

    【讨论】:

    • 非常感谢!最新版本的 EF 中是否已弃用 CreateObjectSet()?
    • .CreateObjectSet()ObjectContext 的一种方法,(据我所知)在 EF 4.1 中被 DbContext 取代
    • 如果这回答了您的问题,请务必将其标记为此类。
    • 我改为entities.Set() 但它仍然给我一个错误:link
    • 非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多