通用存储库,CreateObjectSet< T>()方法 [英] Generic Repository, CreateObjectSet<T>() Method
问题描述
我正在尝试实现一个通用存储库,现在我已经拥有了:
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>();
}
...
我遇到了麻烦调用此方法:
entities.CreateObjectSet< T>();
应该没问题,但是我得到了这个错误:
I'm having trouble with this method call:
entities.CreateObjectSet<T>();
It should be fine, however I get this error:
我已经将System.Data.Entity添加到我的项目,目前我不知道该怎么办。我正在按照本教程 http:// www .codeproject.com / Articles / 770156 /了解存储库和工作单位模式。有人知道如何解决此问题吗?
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?
推荐答案
您将需要更改方法,如下所示:
You will need to change your method to look like this:
public GenericRepository(ApplicationDbContext _entities)
{
entities = _entities;
_objectSet = entities.Set<T>(); //This line changed.
}
这应该具有您想要的功能。
.Set< T>()
是返回所使用类型的 DbSet
的通用方法
This should have the function that you desire.
The .Set<T>()
is the generic method that returns the DbSet
of the type used.
更新:
随着返回类型的更改,您将需要更改 _objectSet
类型。
With the change in return type you will need to change your _objectSet
type as well.
DbSet<T> _objectSet;
这篇关于通用存储库,CreateObjectSet< T>()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!