gpt4 book ai didi

c# - 使用存储库模式获取相关表 Entity Framework

转载 作者:行者123 更新时间:2023-11-30 22:13:37 25 4
gpt4 key购买 nike

我的数据库中有这两个表,并且正在为这个示例使用 Entity Framework

enter image description here

我定义了以下 IRepository 接口(interface)

public interface IRepository<T> where T:class
{
void Add(T entity);
void Update(T entity);
void Delete(T entity);
IQueryable<T> GetAll();
T Find(int id);
}


public class LINQRepository<T> : IRepository<T> where T: class
{

protected DbSet DbSet;


public LINQRepository(DbContext context)
{
DbSet = context.Set<T>();

}

void IRepository<T>.Add(T entity)
{
DbSet.Add(entity);
}

void IRepository<T>.Update(T entity)
{
DbSet.Attach(entity);
}

void IRepository<T>.Delete(T entity)
{
DbSet.Remove(entity);
}

IQueryable<T> IRepository<T>.GetAll()
{

return DbSet as IQueryable<T>;
}


T IRepository<T>.Find(int id)
{

return DbSet.Find(id) as T;

}


}

在我的代码中,我正在实例化一个 QuestionsRepository 并且我还想获​​得返回的问题列表的所有相关答案。我想知道完成这项工作的好方法是什么?我是否在界面中创建另一个函数,如 GetAllWithChild(String ChildName)?我假设有更好的方法来解决这个问题。

最佳答案

在 getAll 方法中,您必须返回 DbSet 并调用该方法。您必须使用 Include(扩展方法)。由于延迟执行的优势,你的查询将被触发一次,你将得到你想要的任何东西..

你必须使用这样的东西

new QuestionsRepository().GetAll().Include("Answers").ToList();

new QuestionsRepository().GetAll().Include(x => x.Answers).ToList();

关于c# - 使用存储库模式获取相关表 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com