1 c# entity-framework repository-pattern
我的存储库模式有问题,它今天早上工作,所以我不明白这是我的代码:
IRepository:
public interface IRepository<T> where T : class
{
List<T> GetAll();
List<T> GetSome(int index, int pageSize);
T GetOne(int id);
T Add(T entity);
void Update(T entity);
void Delete(T entity);
}
Run Code Online (Sandbox Code Playgroud)
IUserRepository:
interface IUserRepository : IRepository<User>
{
}
Run Code Online (Sandbox Code Playgroud)
UserRepository:
public class UserRepository : IUserRepository
{
public User Add(User entity)
{
throw new NotImplementedException();
}
public void Delete(User entity)
{
throw new NotImplementedException();
}
public List<User> GetAll()
{
return new SchoolContext().User.ToList();
}
public User GetOne(int id)
{
throw new NotImplementedException();
}
public List<User> GetSome(int index, int pageSize)
{
throw new NotImplementedException();
}
public void Update(User entity)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
测试文件:
class Program
{
static void Main(string[] args)
{
var source = new User().GetAll();
foreach (var item in source)
{
Console.WriteLine(item.Login);
}
Console.Read();
}
}
Run Code Online (Sandbox Code Playgroud)
我在测试文件中得到的错误是:
用户不包含'GetAll'的定义,也没有扩展方法'GetAll'可以找到'User'类型的第一个参数
我只是想在控制台中显示登录列表,我做错了什么?
你应该创建存储库:
var source = new UserRepository().GetAll();
^
Run Code Online (Sandbox Code Playgroud)
但是你正在创建User实体.
提示:每次调用存储库上的任何方法时,都应该将上下文传递给存储库,并为所有操作使用一个上下文,而不是创建上下文.否则,您必须将实体附加到新上下文以进行修改,因为新上下文不会跟踪实体.并且最好控制上下文的生命周期,以避免在使用延迟加载的实体时出现上下文类型的错误.
public class UserRepository : IUserRepository
{
private SchoolContext db;
public UserRepository(SchoolContext db)
{
this.db = db;
}
public List<User> GetAll()
{
return db.User.ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
更多事件 - 您可以创建基本抽象存储库Repository<T>,它将通过Set<T>上下文方法提供此类常规功能.
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |