首页 > 解决方案 > 如何使用 C# 为 EF6 表定义类编写可为空的属性?

问题描述

我想编写一个 C# 类来描述与其自身相关的数据库表,稍后将与 Entity Framework 6 一起使用。

Contacts表的实体关系图

我有以下 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; }
}

现在,我想标记BelongsToContactNullable,因为这个属性不是必需的。可能有一些联系人属于其他联系人,但也有一些联系人根本不属于任何联系人。该字段应该可以为空。

为了标记BelongsToContact为可为空,我将属性从 type 更改ContactContact?(它是 的更短形式Nullable<Contact>)。

public virtual Contact? BelongsToContact { get; set; }

现在,我收到以下错误:

错误 CS0453 类型“Contact”必须是不可为空的值类型,才能将其用作泛型类型或方法“Nullable”中的参数“T”

那么:如何正确地将属性标记为可选/可为空?最通用的方式(尽可能不使用 Entity Framework 6 标记)。

标签: c#databaseentity-frameworkentity-relationshipentity-relationship-model

解决方案


你应该做这样的事情

    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; }
    }

推荐阅读