【问题标题】:Code First Supress Foreign Key GenerationCode First 禁止外键生成
【发布时间】:2013-01-15 12:54:05
【问题描述】:

我们有一个包含许多实体的数据库,我以三个实体 Case、Task 和 Note 为例。任何实体都可以有注释,我们决定采用以下数据库设计。

Case:
  - CaseId
  - Title

Task:
  - TaskId
  - Title

Note:
  - NoteId
  - Desc
  - ParentId (will contain the PK of Case/Task etc but without FK constraint)

POCO 如下:

Case
{
  CaseId
  Title
  Notes
}

Task
{
  TaskId
  Title
  Notes
}

我们不希望有引用约束,因为这些注释不会被删除。我们可以使用EDMX 对此进行建模,并希望使用 Code First 方法。我们已经搜索了 SO 并查看了多态关联等的建议。如果给定这种设计,首先使用代码建模的最佳方法是什么?提前致谢。

【问题讨论】:

  • 您希望代码优先生成/迁移您的数据库吗?
  • 是的,我们希望根据问题生成数据库。
  • 您不能为创建数据库时 EF 不会尝试转换为 FK 约束的关联建模。您必须手动加入注释,例如在存储库中。

标签: c# ef-code-first entity-framework-5


【解决方案1】:

我建议您使用继承 - 从您的描述中可以看出:

public class EntityWithNotes
{
  public int Id { get; set; }
  public string Title { get; set; }
  public Collection<Note> { get; set; }
}

public class Note
{
  public int Id { get; set; }
  public string Description { get; set; }
  public int ParentId { get; set; }
}

public class Case : EntityWithNotes { /* ...*/ }
public class Task : EntityWithNotes { /* ...*/ }

...并使用外键关联。引用约束不仅仅与删除有关。

【讨论】:

  • 感谢丹尼斯的回复。如果您或有人能指出我们没有/让 ef 生成 FK 的原始问题的方法,我将不胜感激。
猜你喜欢
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多