簡體   English   中英

如何使用C#為EF6表定義類編寫可為空的屬性?

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

我想編寫一個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標記為可為空,我將屬性從Contact類型更改為Contact? (這是Nullable<Contact>Nullable<Contact> )。

public virtual Contact? BelongsToContact { get; set; }

現在,我收到以下錯誤:

錯誤CS0453類型“聯系人”必須是非空值類型,才能在通用類型或方法“空”中將其用作參數“ 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; }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM