【发布时间】:2014-12-23 17:43:19
【问题描述】:
我正在开发一个 asp.net mvc 5 web 项目,我创建了一个存储库模型类来与我的数据库交互,并且我正在从我的操作方法调用我的存储库。例如,在我的 Post Edit 操作方法中,我有以下代码:-
Repository repository = new Repository();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(SecurityRole Role)
{
try
{
if (ModelState.IsValid)
{
repository.InsertOrUpdateRole(Role);
repository.Save();
return RedirectToAction("Index");
}
}}
这里是存储库模型类:-
public class Repository
{
private TEntities tms = new TEntities();
public void InsertOrUpdateRole(SecurityRole role)
{
role.Name = role.Name.Trim();
if (role.SecurityRoleID == default(int))
{
// New entity
//Code goes here
else
{
t.Entry(role).State = EntityState.Modified;
}
}
所以我的问题是,当我将对象从我的操作方法传递到我的存储库时,Entity Framework 将如何处理该对象;它会在存储库中创建另一个副本,还是会跟踪同一个对象?如果实体框架将在会话中的 action 方法和存储库方法中处理同一个对象,那么实体框架如何持续跟踪该对象?
第二个问题,最好的方法是什么;将整个对象从操作方法传递到存储库(正如我目前正在做的那样),或者仅传递对象 id,并在存储库模型中再次检索对象,如下所示:-
repository.InsertOrUpdateRole(Role.RoleID);
在存储库中
public void InsertOrUpdateRole(int id)
{
var SecurityRole = t.SecurityRoles.SingleOrDefault(a => a.SecurityRoleID == role.SecurityRoleID);
}
【问题讨论】:
标签: c# asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-5