C# WCF服务-更新操作最佳实践

C# WCF服务-更新操作最佳实践,c#,wcf,soap,C#,Wcf,Soap,假设我们有一个简单的DTO,要用作CustomerUpdate方法的输入参数: [DataContract] public class CustomerUpdateDTO { [DataMember(IsRequired = true, Order = 0)] public int CustomerId { get; set; } [DataMember(Order = 1)] public string FirstName { get; set; }

假设我们有一个简单的DTO,要用作CustomerUpdate方法的输入参数:

[DataContract]
public class CustomerUpdateDTO
{
    [DataMember(IsRequired = true, Order = 0)]
    public int CustomerId { get; set; }

    [DataMember(Order = 1)]
    public string FirstName { get; set; }

    [DataMember(Order = 2)]
    public string LastName { get; set; }

    [DataMember(Order = 3)]
    public string Address { get; set; }
}
只需要一个字段——CustomerId——这一点很明显,因为我们必须知道要更新哪个客户。我希望实现以下目标:

如果传入的SOAP消息包含给定的值(例如:Joe),则表示客户端希望更新此属性。如果SOAP消息不包含值,则不应更新该值。如果属性的值应该被删除(为null),客户端应该使用nil=“true”属性显式声明(因此显式传递null值)

例如:

<CustomerUpdateDTO>
  <CustomerId>1</CustomerId>
  <FirstName>Joe</FirstName>
  <Address xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
</CustomerUpdateDTO>
所以LastName和Address最终都是空的

有没有办法判断哪些“null”是由于忽略了SOAP消息中的值而导致的,哪些“null”是显式设置的


如果不是,在这种情况下,什么是“最佳实践”?

在谷歌上搜索了一下,我终于找到了问题的答案:)

这是一个非常优雅和简单的解决方案。现在对我来说似乎很明显:)

当SOAP消息被反序列化且值存在时,指定的标志被设置为true

就这样!纯粹的令人敬畏:)

这种格式的消息意味着客户端只想更新FirstName,保持LastName不变,并将地址设置为null

将更新操作分为几个不同的更新操作:

class FirstNameUpdate
    public Customer as integer
    public FirstName as string
end class 

class LastNameUpdate
    public Customer as integer
    public LastName as string
end class

class AddressUpdate
    public Customer as integer
    public Address as string
end class
或者重新发送不变的已知值

dim Customer = Service.GetCustomer(10)

dim CustomerUpdate as new CustomerUpdateDTO with {
    .CustomerID = Customer.ID,
    .FirstName = "Joe",
    .LastName = Customer.LastName,
    .Address = Nothing}

Service.Update(CustomerUpdate)
注意
LastName
取自
Customer
DTO,并在
CustomerUpdate
DTO中发送回服务

class FirstNameUpdate
    public Customer as integer
    public FirstName as string
end class 

class LastNameUpdate
    public Customer as integer
    public LastName as string
end class

class AddressUpdate
    public Customer as integer
    public Address as string
end class
dim Customer = Service.GetCustomer(10)

dim CustomerUpdate as new CustomerUpdateDTO with {
    .CustomerID = Customer.ID,
    .FirstName = "Joe",
    .LastName = Customer.LastName,
    .Address = Nothing}

Service.Update(CustomerUpdate)