【发布时间】:2015-05-12 07:29:48
【问题描述】:
我在我的 ASP.NET-MVC 应用程序中使用存储库模式和工作单元。我在工作单元和控制器类之间有 CRUD 操作和服务类的通用存储库;这意味着控制器类调用工作单元来访问所有操作,这对于封装来自 Web 应用程序的数据访问和业务逻辑非常有用。
现在我的问题是如何在工作单元中获取收集数据。举个例子如下
学生模型
public partial class Student
{
public Student()
{
this.StudentCourses = new HashSet<StudentCourse>();
}
public int StudentID { get; set; }
public string Name { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
课程模式
public partial class Course
{
public Course()
{
this.StudentCourses = new HashSet<StudentCourse>();
}
public int CourseID { get; set; }
public string Title { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
学生课程模式
public partial class StudentCourse
{
[Key]
public int StudentCourseID { get; set; }
[Key]
[ForeignKey("Student")]
public int StudentID { get; set; }
[Key]
[ForeignKey("Course")]
public int CourseID { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
如何使用存储库模式和工作单元实现以下 LINQ 查询结果。我很挣扎,因为通用存储库课程只给学生记录而不是课程,除非我在这里遗漏了一些东西。我使用的数据注释不是流利的 API
using (var db2 = new MyDbContext())
{
List<Student> _studentRead = new List<Student>();
_studentRead = (from _student in db2.Students
.Include(r => r.StudentCourses.Select(sc => sc.Course))
select _student).ToList();
}
通用存储库接口
public interface IGenericRepository<TEntity> where TEntity :class
{
global::System.Linq.IQueryable<TEntity> GetAll();
TEntity GetEntityByID(int id);
void InsertEntity(TEntity obj);
void UpdateEntity(TEntity obj);
void DeleteEntity(int id);
}
通用存储库
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
protected DbSet<TEntity> _DbSet;
private readonly DbContext _dbContext;
public GenericRepository()
{ }
public GenericRepository(DbContext dbContext)
{
this._dbContext = dbContext;
_DbSet = _dbContext.Set<TEntity>();
}
public IQueryable<TEntity> GetAll()
{
return _DbSet;
}
public TEntity GetEntityByID(int id)
{
TEntity obj = _DbSet.Find(id);
return obj;
}
public void InsertEntity(TEntity obj)
{
_DbSet.Add(obj);
}
public void UpdateEntity(TEntity obj)
{
_dbContext.Entry(obj).State = EntityState.Modified;
}
public void DeleteEntity(int id)
{
TEntity obj = _DbSet.Find(id);
_DbSet.Remove(obj);
}
}
【问题讨论】:
-
发布通用存储库的代码。
-
我有更新问题与上面的存储库代码,请查看如下;
标签: c# asp.net-mvc entity-framework repository-pattern unit-of-work