c# - 为什么我们需要声明一个属性才能放置同名的外键属性?
问题描述
如果我必须在引用导航属性上声明一个外键名称,为什么我们需要创建一个原始类型,即 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上只放置一个外键属性?
解决方案
因为这告诉 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 字段并使用它(但这不会在您的模型)
推荐阅读
- javascript - 无法在 React Native 中更改 CheckBox 的状态
- unity3d - Assets\Scripts\GameManager.cs(252,23): error CS0104: 'Random' is a ambiguous reference between 'UnityEngine.Random' 和 'System.Random'
- xamarin.forms - 未呈现自定义组件,因为在 Xamarin 表单上检测到问题
- c++ - 我如何将 char 传递给 pugixml 的 find_child_by_attribute
- python - 操作 CSV 文件中的行数据并使用 Python 将其附加到新列中
- javascript - 使用文件上传获取当前上传的图片并调整大小
- ionic-framework - 无法在 Ionic 4 中设置指纹选项 - 指纹 AIO
- powershell - 下载 powershell 脚本存储库以供离线使用
- windows - 即使 SSH-Add 可以添加新密钥,OpenSSH 也无法提供密钥
- hbase - Apache Sqoop 从 Oracle 导入到 hbase 错误