The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: Unable to set field/property logins on entity type Evalv.Services.employedetail
登录和员工的 Entity Framework 类
public partial class login
{
public string password { get; set; }
public string status { get; set; }
public bool active { get; set; }
public string emailId { get; set; }
public int employeeId { get; set; }
}
public partial class employedetail
{
public employedetail()
{
this.logins = new HashSet<login>();
}
public int employeeId { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
public string emailId { get; set; }
public virtual ICollection<login> logins { get; set; }
}
保存数据的方法
//employedetail e and login l are entity objects with data passed to below method.
public string RegisterUser(employedetail e , login l)
{
try
{
using (EvalvEntities context = new EvalvEntities())
{
context.employedetails.Add(e);
context.logins.Add(l);
if (context.SaveChanges() > 0)
{
return "Registered";
}
else
{
return "Not Registered";
}
}
}
catch(Exception ex)
{
return "Error :" + ex;
}
}
注意:其他一些相同异常的帖子坚持认为这可能是因为缺少主键。但是我有 employedetail
和 login
表的主键和外键。所以不确定出了什么问题。每次我们将实体对象添加到上下文时,我都应该调用 context.SaveChanges()
吗?
例如
context.employedetails.Add(e);
context.SaveChanges();
context.logins.Add(l);
context.SaveChanges();
或者有更好的方法吗? 非常感谢任何帮助。
更新:在记录为 context.savechanges() 生成的查询时,我得到以下查询和异常
INSERT [dbo].[employedetails]([employeeId], [firstName], [middleName], [lastName], [emailId])
VALUES (@0, @1, NULL, @2, @3, )
-- @0: '4567' (Type = Int32)
-- @1: 'sam' (Type = String, Size = 255)
-- @2: 'anderson' (Type = String, Size = 255)
-- @3: 'sam@gmail.com' (Type = String, Size = 255)
-- Executing at 30-12-2016 12:17:27 AM +05:3
-- Completed in 1 ms with result: 1
INSERT [dbo].[login]([employeeId], [emailId], [password], [status], [active])
VALUES (@0, @1, @2, NULL, @3)
-- @0: '4567' (Type = Int32)
-- @1: 'sam@gmail.com' (Type = String, Size = 255)
-- @2: '123456' (Type = String, Size = 255)
-- @3: 'False' (Type = Boolean)
-- Executing at 30-12-2016 12:17:28 AM +05:30
-- Completed in 2 ms with result: 1
抛出异常:EntityFramework.SqlServer.dll 中的“System.InvalidOperationException”
最佳答案
如果您对登录和 EmployeeDetail 类使用一对多关系,那么您缺少 public virtual employedetail employeedetail {get;在登录类中设置;
。
请在您的登录类中添加这一行。(因此您遇到了这个问题。)
public partial class login
{
public string password { get; set; }
public string status { get; set; }
public bool active { get; set; }
public string emailId { get; set; }
public int employeeId { get; set; }
public virtual employedetail employeedetail {get; set;} //Add this in your class
}
注意:- 类(class)名称首字母应大写,并将类(class)名称中的 employedetail 拼写为 EmployeeDetail。
关于c# - 对数据库的更改已成功提交...ObjectContext 可能处于不一致状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41381719/