【问题标题】:Entity Framework 6.1 - Code-First One-to-Many on single entity: Can't map PK to FK?实体框架 6.1 - 单个实体上的代码优先一对多:无法将 PK 映射到 FK?
【发布时间】:2015-04-22 16:58:48
【问题描述】:

我正在尝试首先使用代码在单个表/实体上执行一对多。我的实体看起来像这样并且工作正常:

public class StockIndex
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [StringLength(45, MinimumLength = 3)]
    public string Name { get; set; }

    [StringLength(500)]
    public string Description { get; set; }

    public List<Component> Components { get; set; }

    public StockIndex ParentStockIndex { get; set; }
    public List<StockIndex> StockSubIndices { get; set; }

    public StockIndex()
    {
        StockSubIndices = new List<StockIndex>();
    }
}

它会创建一个带有 PK 和 FK 的表,正如您所期望的那样:

CREATE TABLE [dbo].[StockIndex] (
    [Id]                  INT            IDENTITY (1, 1) NOT NULL,
    [Name]                NVARCHAR (45)  NULL,
    [Description]         NVARCHAR (500) NULL,
    [ParentStockIndex_Id] INT            NULL,
    CONSTRAINT [PK_dbo.StockIndex] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_dbo.StockIndex_dbo.StockIndex_ParentStockIndex_Id] FOREIGN KEY ([ParentStockIndex_Id]) REFERENCES [dbo].[StockIndex] ([Id])
);

效果很好。我已经为它搭建了所有的 CRUD 并且一切正常。但是,这迫使我在进行编辑时在我的控制器中触发一个额外的查询,以便查找并将“父”记录分配给新记录。我想访问表中的“ParentStockIndex_Id”字段,以便我可以直接从下拉列表中分配它并跳过额外的查找查询。我尝试映射它:

public class StockIndex
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [StringLength(45, MinimumLength = 3)]
    public string Name { get; set; }

    [StringLength(500)]
    public string Description { get; set; }

    public List<Component> Components { get; set; }

    public int ParentStockIndex_Id { get; set; }

    [ForeignKey("ParentStockIndex_Id")]
    public StockIndex ParentStockIndex { get; set; }

    public List<StockIndex> StockSubIndices { get; set; }

    public StockIndex()
    {
        StockSubIndices = new List<StockIndex>();
    }
}

但是当我在我的 DbContext 中播种数据时,运行它时出现异常:

无法确定“MyApp.Models.StockIndex_ParentStockIndex”关系的主体端。多个添加的实体可能具有相同的主键。

我确定我做错了什么,但如果可能的话,我想在不使用 Fluent 的情况下这样做。

【问题讨论】:

  • 可能是public int? ParentStockIndex_Id { get; set; },设置Parent 不需要(你有没有看到int 后面的问号)。
  • @tschmit007 呸!就是这样!我知道我也需要使 int 可以为空......完全忘记了它。离开 dotnet 几年了。谢谢!确保将其作为解决方案发布。

标签: sql-server entity-framework ef-code-first


【解决方案1】:

你应该使用public int? ParentStockIndex_Id { get; set; }来设置Parent not required(你有没有看到问号就在int之后)。

【讨论】:

    猜你喜欢
    • 2014-10-20
    • 2011-12-17
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    相关资源
    最近更新 更多