首页 > 解决方案 > 使用带有 ORM 的 DTO 类时,C#8 中的可空引用类型

问题描述

我在具有数据传输对象 (DTO) 类的项目中激活了此功能,如下所示:

public class Connection
    {
        public string ServiceUrl { get; set; }
        public string? UserName { get; set; }
        public string? Password { get; set; }
        //... others 
    }

但我得到了错误:

CS8618:不可为空的属性“ServiceUrl”未初始化。考虑将属性声明为可为空。

这是一个 DTO 类,所以我没有初始化属性。这将是初始化类以确保属性不为空的代码的责任。

例如,调用者可以这样做:

var connection = new Connection
{
  ServiceUrl=some_value,
  //...
}

我的问题:启用 C#8 的可空性上下文时如何处理 DTO 类中的此类错误?

标签: c#ormdtoc#-8.0nullable-reference-types

解决方案


您可以执行以下任一操作:

  1. EF Core建议使用null-forgiving 运算符初始化null!

    public string ServiceUrl { get; set; } = null! ;
    //or
    public string ServiceUrl { get; set; } = default! ;
    
  2. 使用支持字段:

    private string _ServiceUrl;
    public string ServiceUrl
    {
        set => _ServiceUrl = value;
        get => _ServiceUrl
               ?? throw new InvalidOperationException("Uninitialized property: " + nameof(ServiceUrl));
    }
    

推荐阅读