我想编写一个C#类来描述一个数据库表,该表与它本身的关系,稍后用于实体框架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标记为可空,我将属性从Contact类型更改为Contact? (Nullable<Contact>的较短形式)。
public virtual Contact? BelongsToContact { get; set; }现在,我收到以下错误:
错误CS0453类型'Contact‘必须是非空值类型,才能将其用作泛型类型或方法'Nullable’中的参数'T‘。
那么:如何正确地将属性标记为可选/可空?是最通用的方法(如果可能的话不使用实体框架6标记)。
发布于 2019-03-21 16:26:06
你应该这样做
    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; }
    }https://stackoverflow.com/questions/55264180
复制相似问题