Entity Framework 对导航感到困惑 属性

Entity Framework getting confused about navigation property

我正在使用 Entity Framework 6.1.1,我有一个 Users table 和一个 User_Documents table(1:很多)。我已经有了从 User_DocumentsUser 的导航 属性,一切正常。

public partial class User_Document
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long User_Document_ID { get; set; }

    public long User_ID { get; set; }

    [ForeignKey("User_ID")]
    public virtual User User { get; set; }
}

我添加了一个导航 属性 从用户到 User_Documents

public partial class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long User_ID { get; set; }

    [StringLength(50)]
    public string Username { get; set; }

    public virtual List<User_Document> Documents { get; set; }
}

现在我尝试 运行 应用程序时遇到错误:

System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:

User_Documents: Name: Each member name in an EntityContainer must be unique. A member with name 'User_Documents' is already defined.

当然有一个 table 叫 User_Documents 但没有其他 属性 叫这个名字。我不确定它被什么弄糊涂了。也许它正在使用 table 名称 "User" 和 属性 名称 "Documents" 并试图从中创建一个名为 "User_Documents" 的东西?如果我将它重命名为 from Documents Some_Documents 这样

public virtual List<User_Document> Some_Documents { get; set; }

然后我得到一个不同的错误说明

System.InvalidOperationException: The model backing the 'PipeTrackerContext' context has changed since the database was created. Consider using Code First Migrations to update the database

所以我 运行 Add-Migration 我明白了:

public override void Up()
{
    AddColumn("dbo.User_Documents", "User_User_ID", c => c.Long());
    CreateIndex("dbo.User_Documents", "User_User_ID");
    AddForeignKey("dbo.User_Documents", "User_User_ID", "dbo.Users", "User_ID");
}

为什么要尝试添加一个名为 User_User_ID 的新列?为什么我不能像我想要的那样添加 Document 导航 属性?

像这样使用 InverseProperty :

public partial class User_Document
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long User_Document_ID { get; set; }

    public long User_ID { get; set; }

    [ForeignKey("User_ID")]
    [InverseProperty("Documents")]
    public virtual User User { get; set; }
}

并且:

public partial class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long User_ID { get; set; }

    [StringLength(50)]
    public string Username { get; set; }

    [InverseProperty("User")]
    public virtual List<User_Document> Documents { get; set; }
}

Why is it trying to add a new column called User_User_ID? Why can't I just add the Document navigation property like I want?

按照惯例,它会将外键创建为 tablename_columnName,即 User_User_ID。当您删除 [ForeignKey("User_ID")] 属性或没有外键 属性.

时会发生这种情况

如果您将 属性 名称 Documents 更改为其他名称(如 UserDocuments),您将不会遇到这种名称冲突。