我想防止使用Asp.net核心流利性验证更新属于对象的FirstName和LastName属性

问题描述

这是我输入的DTO:

 public class Individual@R_95_4045@ion : IPerson
 {
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public Address PrimaryAddress { get; set; }
     public DateTime? DateOfBirth { get; set; }
     public string CitizenShip { get; set; }
 }

用户尝试使用流利验证来更新名字和姓氏时,我想阻止它。

要做那件事我需要写什么规则?

解决方法

似乎您正在寻找不可变(只读)属性。这是一个示例:

 public class IndividualInformation : IPerson
 {
     public string FirstName { get; }
     public string LastName { get; }
     public Address PrimaryAddress { get; set; }
     public DateTime? DateOfBirth { get; set; }
     public string CitizenShip { get; set; }

    public IndividualInformation(string firstName,string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
 }

var info = new IndividualInformation("Jane","Doe")
{
    PrimaryAddress = ...
};

info.FirstName = "John"; // this will throw an error

如果启用了C#9,则可以为此使用init属性:

 public class IndividualInformation : IPerson
 {
     public string FirstName { get; init; }
     public string LastName { get; init; }
     public Address PrimaryAddress { get; set; }
     public DateTime? DateOfBirth { get; set; }
     public string CitizenShip { get; set; }
 }

var info = new IndividualInformation
{
    FirstName = "Jane",LastName = "Doe",PrimaryAddress = ...
};

info.FirstName = "John"; // this will throw an error