我正在学习 asp.net mvc,并通过了一个很好的教程来演示它。本教程还使用了 Entity Framework 。
我们有自己的数据访问类,我必须使用它。
对于我需要做些什么来弥合我们的类和 MVC 框架之间的差距,我有点困惑。
例如,在教程中,在 MovieController.cs 文件中,有一个 Edit 方法,如下所示:
[HttpPost]
public ActionResult Edit(Movie movie)
{
if (ModelState.IsValid)
{
db.Entry(movie).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
如果我不使用 Entity Framework ,它会是什么样子?我是否仍需要使用 ModelState.IsValid 并像完成状态一样保存状态
db.Entry(movie).State = EntityState.Modified;
请指教。在不使用 Entity Framework 的情况下使用 asp.net mvc 的清晰书面示例会很棒。
我需要知道的是状态在这里扮演什么角色以及它是强制使用还是只是 Entity Framework 运行方式的一部分。
我会将其重写为:
[HttpPost]
public ActionResult Edit(Movie movie)
{
myDBObject.SaveChanges();
return RedirectToAction("Index");
}
其中 myDBObject 是我的自定义数据库访问对象。
最佳答案
您看到的 Controller 直接使用某些数据访问框架(例如 Entity Framework )的示例是不好的示例。整个互联网都被这些东西污染了。我几乎看不到它,我的眼睛会受伤。我认为这些都是不好的做法。数据访问应在存储库中分离和抽象。例如:
public interface IMoviesRepository
{
Movie Get(int id);
void Save(Movie movie);
}
那么你可以使用普通的 ADO.NET、EF、NHibernate、远程 Web 服务调用、一些自定义 ORM 或其他任何东西来实现这个接口(interface):
public class MyCustomFrameworkMoviesRepository: IMoviesRepository
{
...
}
Controller 会将此存储库接口(interface)作为构造函数参数:
public class MoviesController: Controller
{
private readonly IMoviesRepository _repository;
public MoviesController(IMoviesRepository repository)
{
_repository = repository;
}
public ActionResult Index(int id)
{
var movie = _repository.Get(id);
return View(movie);
}
[HttpPost]
public ActionResult Index(Movie movie)
{
if (!ModelState.IsValid)
{
return View(movie);
}
_repository.Save(movie);
return RedirectToAction("Success");
}
}
最后一部分是配置您的依赖注入(inject)框架,以将存储库的正确实现传递给 Controller 。现在您可以看到获取数据的方式与 Controller 逻辑完全分离。这是应该的方式。始终尽量避免应用程序不同层之间的强耦合。
并回答您关于 State 属性的问题:这完全是 EF 特有的,在 Controller 中看到这样的东西真的很遗憾。
为了进一步提高和改进它,您将引入 View 模型。 View 模型是专门为满足给定 View 的要求而设计的类。因此,例如 Movie 是一个域模型。领域模型不应该直接传递给 View 。 Controller Action 不应该将领域模型作为 Action 参数。您应该定义仅包含给定 View 所需的 View 模型,然后执行 View 模型和域模型之间的映射。 AutoMapper 等框架使这非常简单。
关于modelstate - 没有 Entity Framework 的asp.net mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7746075/