Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the problems that are easy to be ignored when updating data by Linq to SQL?

Shulou Source: shulou.com Published: 2022-06-02 09:00:26 09月30日 Update

Xiaobian to share with you Linq to SQL update data easy to ignore what problems, I hope you have something to gain after reading this article, let us discuss it together!

Sometimes, we still use Linq to Sql to update LINQ data. The steps to perform are: Get a record-> Update fields-> submitChanges()

Encountered a problem, the process is not wrong, but LINQ update data has not been updated to the database,

The approximate pseudocode is as follows:

public void UpdateUser(User user) { DataContext context = new DataContext("conn"); User existsUser = GetUser(user.ID); existsUser.Name = user.Name; //............. context.SubmitChanges(); }

Simple code, probably means to get a record, and then update the field, and then submitChanges, generally see no wrong, but!!! We have not found that our context is a private variable, and our GetUser although also obtained from the context, but it uses its own context, that is to say, for the program, it is two objects, so we here in the submitChanges, no matter how you change it is no effect, the database will always not change, My God, perhaps you will think this who does not know ah, but often we really ignore this point, remember the previous exam, Often difficult topics are basically all right, but the simpler the easier the topic, but often make mistakes, I hope these can enlighten you.

Well, now that we know why it went wrong, it's easy to fix it. There are two ways:

LINQ Update Data Method 1:

public void UpdateUser(User user) { DataContext context = new DataContext("conn"); //from the current context User existsUser = context.Users.SingleOrDefault(e => e.ID.Equals(user.ID); existsUser.Name = user.Name; //............. context.SubmitChanges(); }

LINQ Update Data Method 2://Set context to context common DataContext context = new DataContext("conn"); public void UpdateUser(User user) { User existsUser = GetUser(user.ID); existsUser.Name = user.Name; //............. context.SubmitChanges(); } After reading this article, I believe you have a certain understanding of "what problems are easy to ignore when Linq to SQL updates data". If you want to know more about relevant knowledge, please pay attention to the industry information channel. Thank you for reading!

Tags: Update data problem method code field database time article title up and down context two that is finished object meaning effect more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi MariaDB Docker Microsoft Shulou Tech Info