【发布时间】:2017-02-13 01:55:27
【问题描述】:
使用 .net 4.5.2、MVC5、Entity Framework 6 和 Visual Studio 2015。
我有一个使用 Ninject 设置的存储库模式,因为我的 DI 是 common 文件。
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ApplicationDbContext>().ToSelf().InRequestScope();
kernel.Bind<IUserBlueRayLists>().To<UserBlueRayListRepository>().InRequestScope();
kernel.Bind<IBlueRays>().To<BlueRaysRepository>().InRequestScope();
}
我的上下文
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public IDbSet<UserBlueRayList> UserBlueRayLists { get; set; }
public IDbSet<BlueRays> BlueRays { get; set; }
public new void SaveChanges()
{
base.SaveChanges();
}
}
public interface IDevTestContext
{
IDbSet<UserBlueRayList> UserBlueRayLists { get; set; }
IDbSet<BlueRays> BlueRays { get; set; }
void SaveChanges();
}
然后是我的存储库更新方法。
public bool Update(UserBlueRayList item)
{
var userBRList = _db.UserBlueRayLists.FirstOrDefault(x => x.Id == item.Id);
if(userBRList != null)
{
userBRList = item;
//_db.Entry(userBRList).State = EntityState.Modified;
_db.SaveChanges();
return true;
}
return false;
}
现在当我通过我的控制器保存并调用存储库更新方法时,没有任何更新。
所以我用
_db.Entry(userBRList).State = EntityState.Modified;
但我得到一个错误,
附加信息:附加类型为“myapp.Models.UserBlueRayList”的实体失败,因为同一类型的另一个实体已经具有相同的主键值。使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时可能会发生这种情况,如果图中的任何实体具有冲突的键值......等等
多对多模型,用户列表模型。
public class UserBlueRayList
{
public UserBlueRayList()
{
this.BlueRays = new HashSet<BlueRays>();
}
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string UserId { get; set; }
public virtual ICollection<BlueRays> BlueRays { get; set; }
}
还有
public class BlueRays
{
public BlueRays()
{
this.UserBlueRayList = new HashSet<UserBlueRayList>();
}
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public virtual ICollection<UserBlueRayList> UserBlueRayList { get; set; }
}
问题是为什么这不会更新,以及如果我尝试将状态设置为已修改,为什么会出错。
【问题讨论】:
-
userBRList = item行只是替换了实体,但您的上下文并未对其进行跟踪。 -
所以我需要像 userBrList.name = item.Name 一样手动填充它?
-
这是一种方法。您也可以先不从数据库中获取实体,然后附加
item -
什么意思?你能告诉我正确的方法吗?
-
在您的更新方法中,
item(我认为)没有主键或您用作主键的任何索引。简单地用它替换现有记录是行不通的,因此EntityState.Modified行会出错。一种解决方法是手动将所有属性分配到现有记录上,然后保存更改。
标签: c# asp.net-mvc entity-framework asp.net-mvc-5