首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用EF6表定义类为C#编写可空属性?

如何用EF6表定义类为C#编写可空属性?
EN

Stack Overflow用户
提问于 2019-03-20 15:12:51
回答 1查看 103关注 0票数 0

我想编写一个C#类来描述一个数据库表,该表与它本身的关系,稍后用于实体框架6。

我有以下C#代码来实现上述表:

代码语言:javascript
运行
复制
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>的较短形式)。

代码语言:javascript
运行
复制
public virtual Contact? BelongsToContact { get; set; }

现在,我收到以下错误:

错误CS0453类型'Contact‘必须是非空值类型,才能将其用作泛型类型或方法'Nullable’中的参数'T‘。

那么:如何正确地将属性标记为可选/可空?是最通用的方法(如果可能的话不使用实体框架6标记)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-21 16:26:06

你应该这样做

代码语言:javascript
运行
复制
    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; }
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55264180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档