【问题标题】:Unwanted attribute in code-first .NET database代码优先 .NET 数据库中不需要的属性
【发布时间】:2016-12-08 15:36:38
【问题描述】:

我一直在开发 ASP.NET MVC Web 应用程序,但遇到了一个我无法解决的问题。我有以下课程:

public abstract class QuestionAbstract
{
    public int Id { get; set; }
    public int ExamId { get; set; }
    public string Description { get; set; }
    public virtual Exam Exam { get; set; }
    public virtual ICollection<AnswerAbstract> Answers { get; set; }
    public virtual ICollection<Variable> Variables { get; set; }
}

public abstract class AnswerAbstract
{
    [Key, Column(Order = 0)]
    public int ResponseId { get; set; }

    [Key, Column(Order = 1)]
    public int QuestionAbstractId { get; set; }

    [ForeignKey("ResponseId")]
    public virtual Response Response { get; set; }

    [ForeignKey("QuestionAbstractId")]
    public virtual QuestionAbstract Question { get; set; }
}

我希望数据库包括 AnswerAbstract 属性 ResponseId 和 QuestionAbstractId。但是,当创建数据库时,结果是这样的:

CREATE TABLE [dbo].[AnswerAbstract] (
[ResponseId]          INT NOT NULL,
[QuestionId]          INT NOT NULL,
[QuestionAbstract_Id] INT NULL,
CONSTRAINT [PK_dbo.AnswerAbstract] PRIMARY KEY CLUSTERED ([ResponseId] ASC, [QuestionAbstractId] ASC),
CONSTRAINT [FK_dbo.AnswerAbstract_dbo.QuestionAbstract_QuestionAbstractId] FOREIGN KEY ([QuestionId]) REFERENCES [dbo].[QuestionAbstract] ([Id]),
CONSTRAINT [FK_dbo.AnswerAbstract_dbo.Response_ResponseId] FOREIGN KEY ([ResponseId]) REFERENCES [dbo].[Response] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.AnswerAbstract_dbo.QuestionAbstract_QuestionAbstract_Id] FOREIGN KEY ([QuestionAbstract_Id]) REFERENCES [dbo].[QuestionAbstract] ([Id])
);

如您所见,已创建了一个附加属性 (QuestionAbstract_Id),其功能与我编写的 QuestionId 完全相同(引用 QuestionAbstract 类)。我怀疑这与 QuestionAbstract 拥有的 AnswerAbstract 集合有关,但这些类型的关系之前并没有给我带来问题。任何想法为什么会发生这种情况?显然我遗漏了其他类,因为我认为问题不在其他地方,但是如果您需要任何其他代码,请随时询问。

编辑:将 QuestionId 更改为 QuestionAbstractId。还是一样的问题。

【问题讨论】:

  • 尝试将 [ForeignKey("QuestionId")] 更改为 [ForeignKey("QuestionAbstractId")] 以及 public int QuestionId { get;放; } to public int QuestionAbstractId { get;放; }
  • 正如@AzharKhorasany 提到的,您的属性和类名称必须相同(QuestionAbstract 外键不能命名为 QuestionId,它必须命名为 QuestionAbstractId),EF 才能正确映射它们。
  • 刚试了,没用。不过,这似乎是个不错的猜测

标签: c# asp.net asp.net-mvc ef-code-first


【解决方案1】:

尝试改变

[ForeignKey("QuestionId")]

[ForeignKey("QuestionAbstractId")]

还有

public int QuestionId { get; set; }

public int QuestionAbstractId { get; set; } 

【讨论】:

  • 试过了,结果还是一样。
  • @JuanCarlosGuzmánIslas 我已经发布了解决方案,你应该试试那个
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 2013-03-13
相关资源
最近更新 更多