Pet*_*lin 6 c# design-patterns entity-framework coding-style
假设我们已经创建了实体模型,使用它的首选方法是什么?我个人无法下定决心..
使用ModelAdapter:
public stati? Product[] GetProducts()
{
using(Entities ctx = new Entities())
{
return ctx.Product.ToArray();
}
}
Product[] ps = ModelAdapter.GetProducts();
// ...
ModelAdapter.UpdateProduct(p);
Run Code Online (Sandbox Code Playgroud)
使用上下文:
using(Entities ctx = new Entities())
{
Product[] ps = ctx.Product.ToArray();
// ...
ctx.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
混合模式,折衷?
扩展方法:
using(Entities ctx = new Entities())
{
Product[] ps = ctx.GetProducts();
// ...
ctx.UpdateProduct(p);
}
Run Code Online (Sandbox Code Playgroud)实际上现在,我正在尝试方法#4,实现实用程序方法作为上下文的扩展.所以我可以使用一个上下文,并对这个上下文进行多次调用.
在开发Web应用程序时,我一直在使用根据Web请求创建的共享上下文.然后,您可以使用"ModelAdapter"方法并保留封装,但仍然可以在相同的上下文中运行.我经常使用它并且没有遇到任何问题.
通常使用适合您的需求、可维护且适合您的应用程序复杂性的任何内容。您应该考虑以下几点: