且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Enitiy框架更新相关实体

更新时间:2022-11-04 10:25:41

问题是您正在尝试更新来自您的Document对象查看,这不行,因为它只是您数据库中文档的副本;并且删除和重新分配客户的每个文档更新都不行。



因此,在您的控制器类中,您应首先使用文档ID(或其主键)搜索当前文档,然后更新此对象(从数据库上下文)包含来自视图的数据(从您的方法在Document param中缓存的用户输入),最后将其保存到数据库中。这应该可以解决你的问题!



所以你应该有:



The problem is that you are trying to update the Document object that come from your view, and this is not OK, because it just a copy of your document from your database; and also the deleting and the reassigning the customers for each document update is not OK.

So in your controller class you should first search search by using Document ID (or its primary key) the current document, then update this object (that was read from the database context) with data that come from the view (user input that is cached in Document param from your method) and finally save it to the database. This should solve your problem!

So you should have:

public static bool UpdateDocument(Document documentToUpdate)
{
    using (MyDbContext = new MyDbContext())
    {
        Document doc = MyDbContext.FirstOrDefault(d=> d.ID == documetToUpdate.ID)
        //
        //
        CopyUserInputData(documentToUpdate, doc); //You should implement this method that save user input in the given "doc" object!   
        context.SaveChanges();
        return true;
    }
}