簡體   English   中英

我想使用 Asp.net 核心流暢驗證阻止更新屬於對象的 FirstName 和 LastName 屬性

[英]I want to prevent update of FirstName and LastName property which belongs to an object using Asp.net core fluent validations

這是我的輸入 DTO:

 public class IndividualInformation : 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; }
 }

當用戶嘗試使用 fluent 驗證更新名字和姓氏時,我想阻止它。

我需要寫什么規則才能做到這一點?

看起來您正在尋找不可變(只讀)屬性。 下面是一個例子:

 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM