【问题标题】:How to know which Id belongs to which object?如何知道哪个 Id 属于哪个对象?
【发布时间】:2020-07-11 09:53:58
【问题描述】:

我有 3 个外键 ID,它们来自同一个表,所以现在在下面的类中用表名引用它们 - 我怎么知道哪个对象引用了哪个 ID - 例如 Ids

公共部分类 InspectionResult { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] 公共检查结果() { this.EventLogs = new HashSet(); this.InspectionItems = new HashSet(); this.InspectionResultStatCounts = new HashSet(); this.NOVs = new HashSet(); this.UploadedDocuments = new HashSet(); this.AspNetUsers = new HashSet(); } 公共 int InspectionResultId { 获取;放; } 公共字符串 EnteredById { 获取;放; } 公共字符串 CreatedByUserId { 获取;放; } 公共字符串 UpdatedByUserId { 获取;放; } 公共虚拟 AspNetUser AspNetUser { 获取;放; } 公共虚拟 AspNetUser AspNetUser1 { 获取;放; } 公共虚拟 AspNetUser AspNetUser2 { 获取;放; } 公共虚拟 ICollection AspNetUsers { 获取;放; } }

EnteredById、CreatedByUserId、UpdatedByUserId 来自同一个表 AspNetUser,但我怎么知道哪个 Id 属于 AspNetUser、AspNetUser1、、AspNetUser2 以及如何处理 AspNetUsers 对象?我正在使用 EF 数据库优先方法,请提供任何帮助 - 谢谢。

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    您可以使用“ForeignKey”数据注释来表示哪个 Id 属于哪个导航属性。我建议您使用有意义的名称(见下文)来命名您的导航属性,而不仅仅是 1、2、3。

    public string EnteredById { get; set; }
    public string CreatedByUserId { get; set; }
    public string UpdatedByUserId { get; set; }
    
    [ForeignKey("EnteredById")]
    public virtual AspNetUser EnteredBy { get; set; }
    
    [ForeignKey("CreatedByUserId")]
    public virtual AspNetUser CreatedBy { get; set; }
    
    [ForeignKey("UpdatedByUserId")]
    public virtual AspNetUser UpdatedBy { get; set; }
    

    【讨论】:

    • 您好,谢谢 - 我使用的是数据库优先方法 - 字段名称是自动创建的 - 我如何更改它 - 即使我更改它 - 仍然在刷新某些内容时 - 它都会被覆盖对吗?
    • 我已经有一段时间没有先做 DB,但导航属性不是数据库的一部分——它们是实体模型的一部分(在代码中)。这些导航属性的名称可以是您想要的任何名称。您只是无法更改作为数据库一部分的常规属性(EnteredById、CreatedById 等),因为这些属性是从您现有的数据库生成的。
    猜你喜欢
    • 2012-11-18
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2021-02-13
    • 2014-08-05
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多