Dan*_*ton 5 model-view-controller asp.net-mvc separation-of-concerns
我目前正在项目上使用ASP.NET MVC框架(几乎是我第一次)
我使用Linq2SQL作为我的数据模型..
我应该在哪里有这样的代码:
var entries = from e in db.sometable select e;
Run Code Online (Sandbox Code Playgroud)
我目前在控制器中有这样的代码并传递我进入视图的数据..
这个可以吗?
如果不是我如何让我的linq2sql数据模型包含这种代码?
谢谢
丹尼尔
要添加@Poco所说的内容,这是一个例子:
在Foo.Common.Repositories(Foo.Common项目内):
public interface IRepository<T>
{
IEnumerable<T> GetAll();
void Update(T entity);
void Add(T entity);
void Delete(T entity);
void Save();
}
public interface IUserRepository : IRepository<User>
{
void GetByCredentials(string username, string password);
}
Run Code Online (Sandbox Code Playgroud)
内部Foo.Data.Repositories(内部Foo.Data项目):
public class UserRepository
{
// ... other methods/properties snipped.
public IEnumerable<User> GetAll()
{
// Where this.Users would be L2Sql or Code-First... or some other ORM.
return from u in this.Users orderby u.Name select u;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的实际内部Foo.Web:
public class UserController : Controller
{
private readonly IUserRepository userRepository;
public UserController(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult List()
{
var users = this.userRepository.GetAll();
return this.View(users);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的内部你Global.asax有Ninject或其他一些IoC容器来解决IUserRepository:
public static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUserRepository>().To<UserRepository>();
}
protected void Application_Start()
{
var kernel = new StandardKernel();
AreaRegistration.RegisterAllAreas();
MvcApplication.RegisterGlobalFilters(GlobalFilters.Filters);
MvcApplication.RegisterRoutes(RouteTable.Routes);
MvcApplication.RegisterServices(kernel);
// I'm using MVC3 here:
DependencyResolver.SetResolver(new NinjectResolver(kernel));
}
Run Code Online (Sandbox Code Playgroud)
MVC 使用存储库模式是很常见的。通常,您定义一个接口,例如 IProducts,然后实现该接口,调用 linq2sql 代码。您的控制器将接受此接口作为构造函数的参数,以便它依赖于此接口,而不是具体的类。使用依赖注入器(例如 Ninject)将允许您向构造函数提供具体的接口实现。这可以在您的 Web 应用程序上进行单元测试,并且还增加了灵活性。
有一本非常好的书,Pro ASP.NET MVC 2 Framework,解释了这一切。我现在正在读它,我很喜欢它。
| 归档时间: |
|
| 查看次数: |
600 次 |
| 最近记录: |