学校模式
public class School
{
public int SchoolId { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
public virtual ICollection<User> Users { set; get; }
}
用户模型:
public partial class User
{
public int Id { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public virtual School School { get; set; }
public int? SchoolId { get; set; }
}
存储库:
public virtual void Delete(T entityToDelete)
{
if (context.Entry(entityToDelete).State == System.Data.Entity.EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
和控制器
public ActionResult _Delete(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
School school = RepositoryFactory.Create<ISchoolRepository>().Find(id);
if(school == null)
{
return HttpNotFound();
}
return PartialView(school);
}
[HttpPost, ActionName("SchoolDelete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
School school = RepositoryFactory.Create<ISchoolRepository>().Find(id);
RepositoryFactory.Create<ISchoolRepository>().Delete(school);
RepositoryFactory.Create<ISchoolRepository>().SaveChanges();
return RedirectToAction("Index");
}
但是当我尝试删除有用户连接的学校时,我得到了一个前任:
类型&#39; System.Data.Entity.Infrastructure.DbUpdateException&#39;的例外情况发生在EntityFramework.dll中但未在用户代码中处理 附加信息:更新条目时发生错误。有关详细信息,请参阅内部异常
所以我尝试在每个用户学校设置null:
School school = RepositoryFactory.Create<ISchoolRepository>().Find(id);
foreach (var item in school.Users)
{
var user = RepositoryFactory.Create<IUserRepository>().Find(item.Id);
user.School = null;
RepositoryFactory.Create<IUserRepository>().Update(user);
RepositoryFactory.Create<IUserRepository>().SaveChanges();
}
RepositoryFactory.Create<ISchoolRepository>().Delete(school);
RepositoryFactory.Create<ISchoolRepository>().SaveChanges();
但是由于这个原因,我得到了:
类型&#39; System.InvalidOperationException&#39;的例外情况发生在System.Core.dll中但未在用户代码中处理
其他信息:收集已修改;枚举操作可能无法执行。&#34;。
当我在ICollection中没有学生时,这是完美的。
答案 0 :(得分:0)
试试这样。我认为它应该有用。
var school = RepositoryFactory.Create<ISchoolRepository>().Find(id);
var userRepository = RepositoryFactory.Create<IUserRepository>();
for (var i = school.Users.Count - 1; i >= 0; i--)
{
userRepository.Delete(school.Users[i]);
}
RepositoryFactory.Create<ISchoolRepository>().Delete(school);
RepositoryFactory.Create<ISchoolRepository>().SaveChanges();