首页 > 解决方案 > 为什么我们需要声明一个属性才能放置同名的外键属性?

问题描述

如果我必须在引用导航属性上声明一个外键名称,为什么我们需要创建一个原始类型,即 User_ID?

例如

    public class Sims
    {
        public int ID { get; set; }

        public int Users_ID { get; set; }
        [ForeignKey("Users_ID")]
        public Users Users { get; set; }
    }

为什么我需要public int Users_ID { get; set; }Users上只放置一个外键属性?

标签: c#entity-frameworkentity-framework-6

解决方案


因为这告诉 EF 用于存储链接的“用户”记录的 id 的外键字段名为“Users_ID”。
如果您没有明确需要在Sims实体中提供该字段,那么您可以完全忽略它,并且您根本不需要 ForeignKey 属性,EF 将在幕后为您管理。

或者,您可以将外键字段命名为“UsersId”,由于约定,它将假定这是外键。

所以这些中的任何一个都应该完全没问题:

//no explicit foreign key
public class Sims
{
    public int ID { get; set; }
    public Users Users { get; set; }
}

//explicit foreign key but EF works it out via convention
public class Sims
{
    public int ID { get; set; }
    public int UsersId { get; set; }
    public Users Users { get; set; }
}

//explicitly named foreign key which is named differently from 
//convention so needs to be pointed at.  note nameof() operator
//which will give a compiler error should you rename it, so is
//better than a magic string
public class Sims
{
    public int ID { get; set; }

    [ForeignKey(nameof(Users))]
    public int MyUsersFkField { get; set; }        
    public Users Users { get; set; }
}

您还可以将属性添加到Users属性并将其指向 Id 字段。

一个重要的注意事项是,如果您使用非常规命名的 FK 属性并且根本不指定外键,那么 EF 将UsersId在基础数据库中创建一个 FK 字段并使用它(但这不会在您的模型)


推荐阅读