簡體   English   中英

.NET EF Core 模型的 6 個可為 null 的屬性警告

[英].NET 6 nullable properties warnings for EF Core models

我正在使用 EF Core,我有這個 model:

public class Article
{
    public int Id { get; set; }
    public User Author { get; set; } // <- CS8618
    public int AuthorId { get; set; }
}

正如上面的代碼注釋中所指出的,我收到了一個惱人的可為空的警告。 我正在使用 Fluent API 來注釋我的 model,顯然作者不可為空,因為 AuthorId 不可為空。

我覺得使用User? Author 相反, User? Author將警告 go 去掉是不正確的,因為該屬性顯然不可為空,這將是一個謊言,同時也向使用我的 model 的人暗示它可以為空。

處理這種情況的正確方法是什么? 抑制警告?

你會在這個問題上找到很多不同的答案

但在這種特殊情況下,我會問自己一個問題:誰生成了這個類的實例?

1a

如果您 100% 依賴 EF Core 通過查詢數據庫為您生成此類的實例,並且您 100% 確定您始終使用正確的Include() ,我會安全地將Author字段設置為null! ,這意味着它在構造時分配默認值null並自動抑制可空性錯誤。

public class Article
{
    public int Id { get; set; }
    public User Author { get; set; } = null!;
    public int AuthorId { get; set; }
}

1b

您還可以將上述解決方案與私有構造函數一起使用,以保護除 EF Core 之外的其他人將生成此類的實例。

public class Article
{
    private Article()
    {
        Author = null!;
    }

    public int Id { get; set; }
    public User Author { get; set; }
    public int AuthorId { get; set; }
}

2

如果您在代碼的任何其他部分生成此類的實例,則需要一個構造函數來確保Author在構造后永遠不會為空。

public class Article
{
    public Article()
    {
        Author = new User();
    }

    public int Id { get; set; }
    public User Author { get; set; }
    public int AuthorId { get; set; }
}

3

如果您不允許默認的User對象,則期望Authornull是有意義的,但將其標記為Required以確保在寫入數據庫時​​它永遠不會為null

public class Article
{
    public int Id { get; set; }

    [Required]
    public User? Author { get; set; }
    public int AuthorId { get; set; }
}

只需將“#nullable disable”放在命名空間上方即可。

C#11 ( .NET 7.0 ) 開始,您可以添加required的修飾符。

public class Article
{
    public int Id { get; set; }
    public required User Author { get; set; }
    public int AuthorId { get; set; }
}

使用required修飾符,您將無法使用var article= new Article(); 創建一個 object 實例。 因此,它對不可為空的屬性User提供了很好的保護。

現在要創建一個 object 實例,您必須執行如下操作:

var article= new Article()
{
   User = new();
};

最初的答案發布於: What is best way to create .NET6 class with many non-nullable properties?

更詳細的信息: https://learn.microsoft.com/en-us/do.net/csharp/language-reference/keywords/required

暫無
暫無

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

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