[英]Using Repository Pattern for two tables without relation
如何使用 C# 中的存儲庫模式從兩個表中獲取數據,而無需在數據庫中設置它們之間的關系? 例如,我有一張學生表和一張詳細信息表:
public class Student{
public int Id{get;set;}
public string Name{get;set;}
public int GenderId{get;set;}
}
public class DetailsLookup{
public int Id{get;set;}
public string Name{get;set;}
}
我從DetailsLookup.Id
為GenderId
設置數據,但它沒有在數據庫中創建它們之間的關系。
我在我的代碼和工作單元中使用存儲庫模式。 我有一個返回StudentViewModel
的想法。
public class StudentViewModel{
public int Id{get;set;}
public string Name{get;set;}
public int GenderId{get;set;}
public int GenderName{get;set;}
}
但根據我在此處閱讀的內容,我們無法從存儲庫返回視圖模型/DTO。
有人可以幫我弄這個嗎?
如果您擔心從 repo 返回視圖模型,請單獨獲取記錄並將它們合並到服務層中。
存儲庫方法:
public async Task<Student> FetchStudentByIdAsync(int id)
{
return _context.Student.Where(x=>x.Id==id).FirstOrDefaultAsync();
}
public async Task<DetailsLookup> FetchDetailByIdAsync(int id)
{
return _context.DetailsLookup.Where(x=>x.Id==id).FirstOrDefaultAsync();
}
服務方式:
public async Task<StudentViewModel> GetStudentViewModelAsync(int id)
{
var model = new StudentViewModel();
try
{
var student = await _repository.FetchStudentByIdAsync(id);
if(student != null)
{
var detail = await _repository.FetchDetailByIdAsync(student.GenderId);
model.Id = student.Id,
model.Name = student.Name,
model.GenderId = student.GenderId
model.GenderName = detail?.Name
}
}
catch(Exception e)
{
}
return model;
}
正如您在那篇文章中所讀到的,如果您不返回自定義視圖模型,您如何對表執行連接並從多個表返回數據?
更好的方法是連接表並使用對數據庫的一次調用直接從 repo 返回自定義視圖模型。 當您需要包含詳細信息的學生列表時,這是更好的性能。
public async Task<StudentViewModel> FetchStudentViewModelAsync(int id)
{
return await (from s in _context.Student
join d in _context.DetailsLookup on s.GenderId equals d.Id
where s.Id == id
select new StudentViewModel
{
Id = s.Id,
Name = s.Name,
GenderId = s.GenderId
GenderName = d.Name
}).FirstOrDefaultAsync()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.