通用存储库,CreateObjectSet<T>() 方法
Generic Repository, CreateObjectSet<T>() Method
我正在尝试实现一个通用存储库,我现在有这个:
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>();
应该没问题,但是我收到此错误:
我已经将 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>()
是 return 所用类型的 DbSet
的泛型方法。
更新:
随着 return 类型的变化,您还需要更改 _objectSet
类型。
DbSet<T> _objectSet;
我正在尝试实现一个通用存储库,我现在有这个:
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>();
应该没问题,但是我收到此错误:
我已经将 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>()
是 return 所用类型的 DbSet
的泛型方法。
更新:
随着 return 类型的变化,您还需要更改 _objectSet
类型。
DbSet<T> _objectSet;