我有一个具有很多属性的类,可以从外部修改。在设置所有属性的最后,我只想更新数据库中的修改字段,那么有效的方法是什么?
EG。让我们说下面是我的班级
public class SomeClass {
private int field1;
private string field2;
private string field3;
private byte field4;
public int Field1 {
get { return field1; }
set { field1 = value; }
}
public string Field2 {
get { return field2; }
set { field2 = value; }
}
public byte Field4 {
get { return field4; }
set { field4 = value; }
}
public string Field3 {
get { return field3; }
set { field3 = value; }
}
public SomeClass() { }
public bool FillClassVariablesWithCurrentDatabaseValue() {
//Fill the class variables with current database values
}
public bool UpdateModifiedFields() {
//Only update the modified fields in database
}
}
现在要知道该字段是否已更新,我将不得不在类中添加许多布尔变量,如下所示
public class SomeClass {
private int field1;
private string field2;
private string field3;
private byte field4;
private bool field1Updated;
private bool field2Updated;
private bool field3Updated;
private bool field4Updated;
public int Field1 {
get { return field1; }
set {
if (field1 != value) {
field1 = value;
field1Updated = true;
}
}
}
public string Field2 {
get { return field2; }
set {
if (field2 != value) {
field2 = value;
field2Updated = true;
}
}
}
public byte Field4 {
get { return field4; }
set {
if (field4 != value) {
field4 = value;
field4Updated = true;
}
}
}
public string Field3 {
get { return field3; }
set {
if (field3 != value) {
field3 = value;
field3Updated = true;
}
}
}
public SomeClass() { }
public bool FillClassVariablesWithCurrentDatabaseValue() {
//Fill the class variables with current database values
}
public bool UpdateModifiedFields() {
//Only update the modified fields in database
string parameters = string.Empty;
if (field1Updated)
parameters += "field1=@field1";
if (field2Updated)
parameters += "field2=@field2";
if (field3Updated)
parameters += "field3=@field3";
if (field4Updated)
parameters += "field4=@field4";
//code to update these fields
}
}
但由于我的班级有很多变数,我不认为这种方法很好。任何建议都会有所帮助。
答案 0 :(得分:0)
您可以维护
中已更改的属性列表List<string> updatedProperties;
对于在setter中更改的每个属性,请将属性名称添加到List中。最后在Update方法中,循环上面的列表来创建更新逻辑