【发布时间】:2016-04-25 09:36:39
【问题描述】:
我正在尝试 write LINQ to Add or Update 但对我来说 EntityState.Modified 不起作用。
查看我的代码,如果您发现任何错误,请告诉我。 只有新记录插入有效,但更新无效。 我正在使用 EF 6.0。
dbContext _context = new dbContext();
string userName = //getting this value from somewhere else;
string userRoleNo = //getting this value from somewhere else;
Student student = new Student
{
userName = userName,
userRoleNo = userRoleNo,
Date = DateTime.Now
};
bool exist = _context.Students.Any(x => x.UserId == new Guid(userId));
if (exist)
_context.Entry(Student).State = EntityState.Modified;
else
_context.Students.Add(student);
_context.SaveChanges();
【问题讨论】:
-
存在的价值是什么?代码是否属于else部分?
-
查看这种比较 GUID 的方式:stackoverflow.com/questions/5725044/…
-
Harry 存在为真,代码属于 if 部分。 _context.Entry(学生).State = EntityState.Modified;被执行但在表中什么都不做
-
如果条目存在,您需要 Attach() 您创建的学生实例。看看:msdn.microsoft.com/en-us/data/jj592676.aspx
-
我所做的与教程“将现有但已修改的实体附加到上下文”中提到的完全相同
标签: c# entity-framework linq