我有一些 EF 代码来检索控制器中的一些对象,但我想拆分我的函数以提高代码重用性。
我的代码目前看起来像这样:
public ActionResult SentMessages(){
MyModel model = new MyModel();
int user_id = GetCurrentUserId();
using(DataContext db = new DataContext()){
model.Messages =
db.Messages
.Where(x => x.sent == true)
.Where(x => x.user_id == user_id)
.Where(x => x.date_deleted == null)
.OrderBy(x => x.date_sent)
.Take(10)
.ToList();
model.Groups = db.Groups
.Where(x => x.user_id == user_id)
.Where(x => x.date_deleted == null)
.OrderBy(x => x.date_created)
.ToList();
}
return model;
}
我想把它分成可重用的代码块,(并使我的控制器更小)像这样
public ActionResult SentMessages(){
MyModel model = new MyModel();
int user_id = GetCurrentUserId();
model.Messages = GetLastTenMessages(user_id);
model.Groups = GetGroups(user_id);
return model;
}
public static List<Message> GetLastTenMessages(int user_id){
using(DataContext db = new DataContext()){
return db.Messages
.Where(x => x.sent == true)
.Where(x => x.user_id == user_id)
.Where(x => x.date_deleted == null)
.OrderBy(x => x.date_sent)
.Take(10)
.ToList();
}
}
public static List<Group> GetGroups(int user_id){
using(DataContext db = new DataContext()){
return db.Groups
.Where(x => x.user_id == user_id)
.Where(x => x.date_deleted == null)
.OrderBy(x => x.date_created)
.ToList();
}
}
但是,这会导致与数据库的两个单独连接(据我所知)。每个查询打开和关闭一个。
有没有办法将上下文传递给方法,像这样
public ActionResult SentMessages(){
MyModel model = new MyModel();
int user_id = GetCurrentUserId();
using(DataContext db = new DataContext()){
model.Messages = GetLastTenMessages(user_id, db);
model.Groups = GetGroups(user_id, db);
}
return model;
}
public static List<Message> GetLastTenMessages(int user_id, DataContext db){
return db.Messages
.Where(x => x.sent == true)
.Where(x => x.user_id == user_id)
.Where(x => x.date_deleted == null)
.OrderBy(x => x.date_sent)
.Take(10)
.ToList();
}
public static List<Group> GetGroups(int user_id, DataContext db){
return db.Groups
.Where(x => x.user_id == user_id)
.Where(x => x.date_deleted == null)
.OrderBy(x => x.date_created)
.ToList();
}
有没有这样的事情我可以这样做,这样我既可以分离出我的代码,也可以使用尽可能少的数据库连接数?