【发布时间】:2012-03-05 08:39:12
【问题描述】:
我构建了一个非常简单的 MVC3 应用程序来做一个小演示,但是我遇到了一个问题;我将一个实体返回到我的视图中,对其进行编辑然后将其发布回来,但在此过程中,我的实体失去了它的更改跟踪功能。当我将实体返回到我的视图时,它仍然是一个实体框架代理类,但是当它从我的视图中返回时,它是一个“Person”类(实体称为 person)。
这是我的存储库类:
public class PersonRepository : IPersonRepository
{
public EfContext Uow { get; set; }
public PersonRepository(IUnitOfWork uow)
{
Uow = uow as EfContext;
}
// yada yada yada
public void Add(Person person)
{
Uow.Persons.Add(person);
}
}
这个实体被发送到我的视图,它有一个简单的表单,用 Html.EditorForModel 创建。之后我把它发回这个方法:
[HttpPost]
public ActionResult Edit(Person person)
{
if (ModelState.IsValid)
{
_personRepository.Add(person);
_personRepository.Uow.Commit();
return RedirectToAction("Index");
}
return View(person);
}
还有,它不再是一个跟踪代理类。这会导致主键违规,因为实体框架试图将我的对象添加为新对象,而我只希望实体框架检测更改并创建更新语句。哦对了,上面代码中的Commit方法只是调用了SaveChanges(),下面是类:
public class EfContext : DbContext, IUnitOfWork
{
public DbSet<Account> Accounts { get; set; }
public DbSet<Person> Persons { get; set; }
public void Commit()
{
SaveChanges();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
顺便说一下,这是我的实体类:
public class Person
{
[HiddenInput(DisplayValue = false)]
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Account> Accounts { get; set; }
}
有谁知道如何解决这个问题?据我所知,我以前有过这个工作,我只是不知道怎么做。
提前致谢!
【问题讨论】:
标签: c# asp.net-mvc-3 entity-framework frameworks entity