代码优先抑制外键生成

时间:2013-01-15 12:54:06

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

我们有一个包含许多实体的数据库,我正在举例说明三个实体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并查看了多态关联的建议等。如果给出这种设计,首先使用代码进行建模的最佳方法是什么?提前谢谢。

1 个答案:

答案 0 :(得分:0)

我建议您使用继承 - 它来自您的描述:

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 { /* ...*/ }

...并使用外键关联。参考约束不仅仅是删除。