如何使用 C# 为 EF6 table 定义 class 编写可空属性?

How to write nullable properties for EF6 table definition class with C#?

我想写一个 C# class 来描述一个与其自身有关系的数据库 table,稍后用于 Entity Framework 6.

我有以下 C# 代码来实现上面显示的 table:

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 标记为可为空,我将 属性 从类型 Contact 更改为 Contact?(这是 Nullable<Contact> 的缩写形式)。

public virtual Contact? BelongsToContact { get; set; }

现在,我收到以下错误:

Error CS0453 The type 'Contact' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'

所以:如何正确地将 属性 标记为 optional/nullable? 最通用的方法(尽可能不使用 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; }
    }