使用.net 4.5.2、MVC5、Entity Framework 6 和 Visual Studio 2015。
我使用 Ninject 设置了一个存储库模式,因为这里的 DI 是通用文件。
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;
}
现在,当我通过 Controller 保存并调用存储库更新方法时,没有任何更新。
所以我使用
_db.Entry(userBRList).State = EntityState.Modified;
但是我收到错误,
Additional information: Attaching an entity of type 'myapp.Models.UserBlueRayList' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values... etc
多对多模型,用户列表模型。
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; }
}
问题是为什么这不会更新,以及为什么如果我尝试将状态设置为已修改会出错。
最佳答案
由于您使用的是 EF6,因此您可以尝试使用 EF6 内置的自动属性映射
public bool Update(UserBlueRayList item)
{
var userBRList = _db.UserBlueRayLists.FirstOrDefault(x => x.Id == item.Id);
if(userBRList != null)
{
_dbContext.Entry(userBRList).CurrentValues.SetValues(item);
return return _dbContext.SaveChanges() > 0;
}
return false;
}
干杯
关于c# - Entity Framework 更新未保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42195542/