c# - 使用带有 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 类中的此类错误?
解决方案
您可以执行以下任一操作:
EF Core建议使用null-forgiving 运算符初始化
null!
public string ServiceUrl { get; set; } = null! ; //or public string ServiceUrl { get; set; } = default! ;
使用支持字段:
private string _ServiceUrl; public string ServiceUrl { set => _ServiceUrl = value; get => _ServiceUrl ?? throw new InvalidOperationException("Uninitialized property: " + nameof(ServiceUrl)); }
推荐阅读
- javascript - chess.com API 不会带回一些请求
- c# - 防止 XmlDocument 解释 HTML 代码
- php - using arabic words in pdf
- unity3d - C# Unity 我怎么能每秒都做点什么?
- java - 使用 itextpdf 时在 pdf 文件中定位坐标文本
- java - 基于 Java 的 azure 函数的 Swagger 生成
- flutter - 在 Flutter 中,如何删除小部件的一部分。我想删除容器小部件的下半部分
- css - 如果 scss 中的输入为空,如何禁用或忽略代码
- c++ - 每次打开组合框时如何创建项目列表?
- c++ - 我如何找到长度?我有 8 个管子和 11 个节点