Skip to main content
 首页 » 编程设计

c#之是否有任何 linqish 方式来保存用户表单数据之重构我的代码

2024年02月13日10小虾米

我有一个简单的表单,它获取用户数据并将其保存到数据库中。虽然它工作正常但看起来很重复..我不确定我是否可以以某种方式转换我的代码以检查用户输入并将其保存在数据库中。

这是我的代码..

public void SaveUserData() 
      { 
            MWCompetitionContestantsDetails user = new MWCompetitionContestantsDetails(); 
            MWCompetitionsEntryDetails entry = new MWCompetitionsEntryDetails(); 
 
            if (!IsNullOrEmpty(firstNameText.Value)) 
                  user.FirstName = firstNameText.Value; 
            if (!IsNullOrEmpty(lastNameText.Value)) 
                  user.LastName = lastNameText.Value; 
            if (!IsNullOrEmpty(emailText.Value)) 
                  user.UserEmailAddress = emailText.Value; 
            if (!IsNullOrEmpty(address1Text.Value)) 
                  user.Address1= address1Text.Value; 
            if (!IsNullOrEmpty(address2Text.Value)) 
                  user.Address2 = address2Text.Value; 
            if (!IsNullOrEmpty(cityText.Value)) 
                  user.City = cityText.Value; 
            if (!IsNullOrEmpty(provinceText.Value)) 
                  user.Province= provinceText.Value; 
            if (!IsNullOrEmpty(postCodeText.Value)) 
                  user.PostalCode = postCodeText.Value; 
            if (!IsNullOrEmpty(countryText.SelectedItem.Text)) 
                  user.Country = countryText.SelectedItem.Text; 
 
            user.Save(); 
      } 
 
      public static bool IsNullOrEmpty<T>(T value) 
      { 
            if (typeof(T) == typeof(string)) 
                  return string.IsNullOrEmpty(value as string); 
 
            return value.Equals(default(T)); 
      }  

而不是在每个字段上寻找 IsNullOrEmpty(data),是否有任何建议使用 Linq 或任何东西来改进我的代码..

非常感谢您的宝贵时间...

请您参考如下方法:

您可以在属性的 setter 中检查 If null 或 empty:

public class MWCompetitionContestantsDetails 
{ 
    private string _firstName; 
 
    public string FirstName 
    { 
        get 
        { 
            return this._firstName; 
        } 
        set 
        { 
            if(!IsNullOrEmpty(value)) 
            { 
                this._firstName = value; 
            } 
        } 
    }        
 
    ......... 
 
    public static bool IsNullOrEmpty<T>(T value) 
    { 
        if (typeof(T) == typeof(string)) 
              return string.IsNullOrEmpty(value as string); 
 
        return value.Equals(default(T)); 
    }  
}