简体   繁体   English

使用Linq更新记录

[英]Updating record with Linq

I have a question regarding Linq and updating a record in the database. 我有一个关于Linq和更新数据库记录的问题。 I don't know how to update a record when the fields that you use are not known. 当您使用的字段未知时,我不知道如何更新记录。 It is hard for me to explain this so I use the following example: 我很难解释这个,所以我使用以下示例:

Customer c = (from x in dataBase.Customers
             where x.Name == "Test"
             selext x).First();
c.Name = "New Name";
dataBase.SaveChanges();

In this example you'll update the name field in the table Customers in the database. 在此示例中,您将更新数据库中Customers表中的名称字段。 Lets say that Customer has an ID, a name and a phone number. 让我们说客户有一个ID,一个名字和一个电话号码。 In the example you'll only update name in the database. 在示例中,您只会更新数据库中的名称。 And if I want to update the phone number I'll just add c.Phonenumber = 01234; 如果我想更新电话号码,我只需添加c.Phonenumber = 01234; and it will also update the phone number. 它还会更新电话号码。

Now, the user uses text boxes to fill in new data, however, it is not required to change all data. 现在,用户使用文本框填充新数据,但是,不需要更改所有数据。 So you can update name and phone number, or either one of them. 因此,您可以更新姓名和电话号码,或其中任何一个。 The problem that I have is that I don't know how to determine what the user filled in and how to determine what fields to select and update. 我遇到的问题是我不知道如何确定用户填写的内容以及如何确定要选择和更新的字段。 If I have a customers table with 10 different fields it is possible that a user wants to change 8 fields and I don't know how to tell the program that it has to update those 8 fields. 如果我有一个包含10个不同字段的customers表,那么用户可能想要更改8个字段,而我不知道如何告诉程序它必须更新这8个字段。 I hope you can understand my explanation and can help me with this. 我希望你能理解我的解释,并能帮助我。 Thanks in advance. 提前致谢。

Your ObjectContext will keep track of changes for you. 您的ObjectContext将跟踪您的更改。 It does this because all your entities (eg Customer ) will inherit EntityObject and INotifyPropertyChanged 这样做是因为所有实体(例如Customer )都将继承EntityObjectINotifyPropertyChanged

Calling SaveChanges will persist all the changes to the database in a transaction. 调用SaveChanges将在事务中保留对数据库的所有更改。

This mean that you don't need to keep track of changes - EF does that for you. 这意味着您不需要跟踪更改 - EF会为您执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM