c# - 如何使用 C# 为 EF6 表定义类编写可为空的属性?
问题描述
我想编写一个 C# 类来描述与其自身相关的数据库表,稍后将与 Entity Framework 6 一起使用。
我有以下 C# 代码来实现上面显示的表格:
public class Contact
{
/// <summary>
/// Unique identifier of the contact.
/// </summary>
public string ContactId { get; set; }
/// <summary>
/// Gets or sets the name of the contact.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Defines whether the contact belongs to another contact (e.g.,
/// parents, organization).
/// </summary>
public virtual Contact BelongsToContact { get; set; }
}
现在,我想标记BelongsToContact
为Nullable
,因为这个属性不是必需的。可能有一些联系人属于其他联系人,但也有一些联系人根本不属于任何联系人。该字段应该可以为空。
为了标记BelongsToContact
为可为空,我将属性从 type 更改Contact
为Contact?
(它是 的更短形式Nullable<Contact>
)。
public virtual Contact? BelongsToContact { get; set; }
现在,我收到以下错误:
错误 CS0453 类型“Contact”必须是不可为空的值类型,才能将其用作泛型类型或方法“Nullable”中的参数“T”
那么:如何正确地将属性标记为可选/可为空?最通用的方式(尽可能不使用 Entity Framework 6 标记)。
解决方案
你应该做这样的事情
public class Contact
{
/// <summary>
/// Unique identifier of the contact.
/// </summary>
public string ContactId { get; set; }
/// <summary>
/// Gets or sets the name of the contact.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Defines whether the contact belongs to another contact (e.g.,
/// parents, organization).
/// </summary>
[ForeignKey("BelongsToContact")]
public int? BelongsToContactId { get; set; }
public virtual Contact BelongsToContact { get; set; }
}
推荐阅读
- matlab - 使用randi(或其他东西)控制比例
- python - 使用 Selenium 从 div 标签中获取文本时遇到问题
- node.js - Heroku 无法使用 bcrypt 部署 node.js
- java - 在 Heroku Java 上运行 Selenium
- react-native - React Native Picker 组件与 React hook:无法将 Picker 的值传递给父级
- json - 支持遍历的二进制 JSON 格式
- docker - 有没有办法在运行 raspbian 的覆盆子 pi4 上的 docker 上运行 jenkins 容器?
- xml - 将唯一字符串替换为
整理 xslt 中的标签 - javascript - 如何减少两个数组以获取自定义对象
- rest - 如何访问 GIT LAB 提供的 REST API?