【问题标题】:With httpPut to skip that column if .net core is null or null如果 .net core 为 null 或 null,则使用 httpPut 跳过该列
【发布时间】:2021-09-13 11:42:33
【问题描述】:

我正在使用 .NET Core 开发微服务。 以下代码正在处理 HttpPut 请求。 但是,如果我们传入的 JSON 请求中有任何字段为空或 null 值,我希望它检索以前的值。

我不想经常运行下面的代码。有没有捷径可以解决这个问题?

if(updateCustomer.Surname != null && updateCustomer.Surname !=string.Empty)
{
    customer.Surname = updateCustomer.Surname;
}

var serviceResponse = new ServiceResponse<GetCustomerDto>();
Customer customer = await _context.Customers.FirstOrDefaultAsync(c => c.Id == updateCustomer.Id);

var persons = (from p in  _context.Customers where p.Id == updateCustomer.Id select p);
foreach (var person in persons)
{
    person.Name = updateCustomer.Name;
    person.Surname = updateCustomer.Surname;
    person.BusinessCode = "123";
    person.Phone = updateCustomer.Phone;
}
await _context.SaveChangesAsync();

serviceResponse.Data = _mapper.Map<GetCustomerDto>(customer);

【问题讨论】:

  • 听起来您正在寻找一种代码成语来使您的代码更具可读性。那是对的吗?如果是这样,对于可空类型,有GetValueOrDefault()。对于没有该方法的类型,您可以创建一个扩展方法,或者只是一个通过参数是否为空来确定其返回值的方法。
  • 是的,伙计。但是你能举个例子吗?

标签: c# .net linq asp.net-core microservices


【解决方案1】:

按照Nullable 类型中的GetValueOrDefault() 习惯用法,您可以创建一个字符串扩展方法来在两个值之间进行选择,如下所示:

public static class StringExtensions 
{
    public static string GetValueOrDefault(this string str, string alternative)
    {
        if(string.IsNullOrEmpty(str))
        {
            return alternative;
        }
        
        return str;
    }   
}

public class Program
{
    public class Person 
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public string BusinessCode { get; set; }
        public string Phone { get; set; }
    }
    
    public static void Main()
    {
        Person previous = new Person
        {
            Name = null,
            Surname = "Smith",
            BusinessCode = "123",
            Phone = "(555) 123-4567"
        };
        
        Person current = new Person
        {
            Name = "John",
            Surname = string.Empty,
            BusinessCode = "321",
            Phone = "(555) 765-4321"
        };
        
        Person updated = new Person
        {
            Name = current.Name.GetValueOrDefault(previous.Name),
            Surname = current.Surname.GetValueOrDefault(previous.Surname),
            BusinessCode = current.BusinessCode.GetValueOrDefault(previous.BusinessCode),
            Phone = current.Phone.GetValueOrDefault(previous.Phone)
        };
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多