Generic Repository, CreateObjectSet<T>() Method

帅比萌擦擦* 提交于 2019-12-20 01:34:35

问题


I was trying to implement a generic repository, and I have this right now:

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>();
        }

        ...

I'm having trouble with this method call: entities.CreateObjectSet<T>(); It should be fine, however I get this error:

I have already added the System.Data.Entity to my project and at this point I don't know what else to do. I am following this tutorial http://www.codeproject.com/Articles/770156/Understanding-Repository-and-Unit-of-Work-Pattern. Does anyone know how to fix this issue?


回答1:


You will need to change your method to look like this:

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

This should have the function that you desire. The .Set<T>() is the generic method that returns the DbSet of the type used.

UPDATE:

With the change in return type you will need to change your _objectSet type as well.

DbSet<T> _objectSet;


来源:https://stackoverflow.com/questions/37240128/generic-repository-createobjectsett-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!