这是一个非常常见的错误,但没有一个帖子回答了我的问题,因此创建了它。
我在ViewModel中有一个函数Foo(),它首先调用存储过程,然后修改上下文并尝试保存上下文。当我保存上下文时,我遇到了错误。对我来说,在调用存储过程后保存上下文很重要。
如果有任何想法可以解决这个问题?
public class UserViewModel
{
private AbcRepository _repo;
public void UserViewModel(AbcRepository repo){
_repo = repo;
}
Foo()
{
user_table user =_repo.CreateNewEmptyUser();
user.Name = "Test";
_repo.AddEntryToShipping("TestUser", 22);
//After _repo.AddEntryToShipping which calls stored procedure
// i need to update the updateTime column value and then
// save the context.
user.updateTime = DateTime.now();
_repo.save();
}
}
public class AbcRepository
{
public AbcRepository(AbcEntities context)
{
_context = context;
}
public void Save()
{
_context.Save();
}
public void AddEntryToShipping(string userName, int age)
{
//AddEntryToShipping is stored procedure, which adds the new entry to shipping table etc
var result = _context.AddUser(userName, age);
}
public user_table CreateNewEmptyUser()
{
user_table newUser = _context.user_table.Create();
_context.user_table.Add(newUser);
return newUser;
}
}
如何创建上下文:
我有一个处理程序,它创建上下文并初始化必要的Vms,
Public class StartUpClass{
public StartUpClass()
{
AbcEntities context = new AbcEntities(connectionString);
AbcRepository repo = new AbcRepository(context);
UserViewModel uv = new UserViewModel(repo;)
}
}
public partial class AbcEntities: DbContext
{
public AbcEntities(): base("name=AbcEntities")
{
}
public virtual DbSet<user_table > user_table { get; set; }
}
public partial class AbcEntities
{
public AbcEntities(string sqlConnectionString):base(sqlConnectionString)
{
}
public bool Save()
{
return true;
}
}