【问题标题】:Adding a Foreign Key referencing AspNetUser when creating a table using Code First - MVC5使用 Code First 创建表时添加引用 AspNetUser 的外键 - MVC5
【发布时间】:2019-06-23 08:18:45
【问题描述】:

我正在创建一个 Visual Studios MVC5 Web 应用程序,并尝试将 AspNetUser 表中的 id 作为外键引用。

我正在创建一个新表:

public class Patient
{
    public int PatientId { get; set; }
    public string HCN { get; set; }
    public string GP { get; set; }
    public string MedHis { get; set; }
    public string Medication { get; set; }
    public string CurrentPrescription { get; set; }
    public string PresentRX { get; set; }

    [ForeignKey("UserId")]
    public virtual ApplicationUser UserId { get; set; }
}

我的Patient 配置类:

public class PatientConfig : EntityTypeConfiguration<Patient>
{
    public PatientConfig()
    {
        ToTable("Patient");

        Property(x => x.PatientId).HasColumnName("IntId");
        HasKey(x => x.PatientId);

        Property(x => x.HCN).HasColumnName("strHCN");
        Property(x => x.GP).HasColumnName("strGP");
        Property(x => x.MedHis).HasColumnName("strMedHis");
        Property(x => x.Medication).HasColumnName("strMedication");

        Property(x => x.CurrentPrescription).HasColumnName("strCurrentPrescription");

        Property(x => x.PresentRX).HasColumnName("strPresentRX");
        Property(x => x.UserId).HasColumnName("intUserId");
    }
}

首先我得到了错误

必须是不可为空的值类型才能将其用作参数

UserId 属性下面,所以我将其删除了

Property(x=> x.UserId).HasColumnName("intUserId");

当我尝试添加迁移时,出现以下错误:

类型“ModelTest.Models.Patient”的属性“UserId”上的 ForeignKeyAttribute 无效。在依赖类型“ModelTest.Models.Patient”上找不到外键名称“UserId”。 Name 值应该是一个逗号分隔的外键属性名称列表。

我不明白为什么找不到UserId,任何建议将不胜感激。

谢谢

【问题讨论】:

    标签: c# asp.net-mvc entity-framework visual-studio-2013


    【解决方案1】:

    这与任何其他关系一样有效。 ApplicationUser 没有什么特别之处。看来您一开始并不真正了解如何设置实体框架关系。

    如果您关心有一个可以在应用程序中访问的显式外键属性,那么您需要添加到实体中的只是:

    public virtual ApplicationUser User { get; set; }
    

    这将导致实体框架在您的实体表上生成一个隐式外键,但您将无法直接在您的应用程序中访问此值。 User 将是 ApplicationUser 的完整实例。

    如果您确实想直接访问外键属性,那么您需要类似:

    [ForeignKey("User")]
    public string UserId { get; set; }
    public virtual ApplicationUser User { get; set; }
    

    现在,除了允许您访问适当的ApplicationUser 实例的导航属性之外,实体上还有一个实际属性来保存外键值。

    虽然实体框架实际上应该能够按照惯例自行确定 UserIdUser 导航属性的外键,但我发现使用 ForeignKey 属性始终明确会更好。

    另外,请注意UserId 的类型是string。这是 IdentityUser 默认使用的类型作为主键。如果您愿意,您可以更改它,但如果您只使用标准部署,那么它将是 string 而不是像 int 这样的东西,您似乎认为它会在您的代码中。

    【讨论】:

      【解决方案2】:
      [ForeignKey("User")]<br/>
      public string UserId { get; set; }<br/>
      public virtual ApplicationUser User { get; set; }
      

      当我将以上几行添加到类中,然后迁移和更新数据库时,
      我创建了 ApplicationUser 表!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-31
        • 1970-01-01
        • 1970-01-01
        • 2016-03-14
        • 1970-01-01
        • 2012-03-04
        • 1970-01-01
        相关资源
        最近更新 更多