More and more friends prefer to use LINQ to SQL for development projects. We generally encounter crud and other operations. It is undeniable that, in terms of query, LINQ really brings great convenience, the performance is also good. In insert and delete operations, the performance of LINQ is also good, but when updating a record, the performance is relatively weak, we generally use executesql and other methods to execute the script.
However, sometimes we still use LINQ to SQL for update. The procedure is as follows: Get a record-> Update field-> submitchanges ()
I encountered a problem yesterday and the process was correct, but it was never updated to the database during the update,
Probably falseCodeAs follows:
Public void updateuser (User user) {< br> datacontext context = new datacontext ("conn"); User existsuser = getuser (user. ID); existsuser. name = user. name; //............. context. submitchanges (); } |
The simple code, probably means getting a record, updating the field, and then submitchanges. Let's take a look at the error, !!!! Have you noticed that our context is a private variable, while our getuser is also obtained from context, but it uses its own context, that is,ProgramFor example, it is two objects, so no matter how you change it in submitchanges, it will never change in the database, my God, maybe you don't know this, but we often ignore this point. Remember that the previous exams are usually difficult questions, but the simpler the easier the questions, but I often make mistakes. I hope these will inspire you.
Now, you know why the error occurred and the modification is simple. There are two methods:
Method 1: Public void updateuser (User user) {< br> datacontext context = new datacontext ("conn"); // obtain from the current context User existsuser = context. users. singleordefault (E => E. id. equals (user. ID); existsuser. name = user. name; //............. context. submitchanges (); } Method 2: // set context to context Public datacontext context = new datacontext ("conn "); Public void updateuser (User user) { User existsuser = getuser (user. ID); existsuser. name = user. name; //............. context. submitchanges (); } |
Tags: C #, LINQ to SQL, careful, Project
Okay,ArticleIt is relatively simple, and you may think it is not worth mentioning. It is not for the purpose of solving this problem. I hope that you will be careful when working on projects, because you may have a small negligence, unpredictable consequences for projects and companies.