界面
public interface IDinnerRepository
{
IQueryable<Dinner> FindAllDinners();
IQueryable<Dinner> FindDinnersByText(string q);
Dinner GetDinner(int id);
void Add(Dinner dinner);
void Delete(Dinner dinner);
void Save();
}
从上述接口继承的类
public class DinnerRepository : NerdDinner.Models.IDinnerRepository
{
NerdDinnerEntities db = new NerdDinnerEntities();
Public IQueryable<Dinner> FindDinnersByText(string q)
{
return db.Dinners.Where(d => d.Title.Contains(q)
|| d.Description.Contains(q)
|| d.HostedBy.Contains(q));
}
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}
public void Add(Dinner dinner)
{
db.Dinners.AddObject(dinner);
}
public void Delete(Dinner dinner)
{
foreach (RSVP rsvp in dinner.RSVPs.ToList())
db.RSVPs.DeleteObject(rsvp);
db.Dinners.DeleteObject(dinner);
}
public void Save()
{
db.SaveChanges();
}
}
在程序中的使用
public class DinnerOperation
{
DinnerRepository dr = new DinnerRepository();
// insert
public void InsertDinner()
{
Dinner dinner = dr.GetDinner(5);
dr.Dinner.Add(dinner);
dr.Save();
}
// delete
public void DeleteDinner()
{
Dinner dinner = dr.GetDinner(5);
dr.Dinner.Delete(dinner);
dr.Save();
}
}
并且不使用存储库设计模式......
public class DinnerOperation
{
DinnerEntities entity = new DinnerEntities();
// insert
public void InsertDinner()
{
Dinner dinner = entity.Dinners.Find(5);
entity.Dinner.Add(dinner);
entity.SaveChanges();
}
// delete
public void DeleteDinner()
{
Dinner dinner = entity.Dinners.Find(5);
entity.Dinner.Remove(dinner);
entity.SaveChanges();
}
}
问题
我无法理解,在这里,我们为什么要使用设计模式?当以这种方式将存储库设计模式与实体框架一起使用时,没有任何意义。
如何将设计模式与实体框架一起使用?什么时候将设计模式与实体框架一起使用才有意义?