3

在我们的数据库中,我们有以下表格

Tags
  Id (int)
  Name (string)
  IsActive (bool)
  TagType (string)

DocumentStyles
  Id (int)
  Name (string)
  StyleRules (string)
  IsAvailable (bool)
  ThumbnailFileId (int nullable)
  ConceptTagId (int nullable)

使用 EF 4.2 设计器,我创建了适当的实体,并尝试将 ConceptTagId 的外键链接到 Tag 模型。

当我添加关联(从 Tag 到 DocumentStyle 的 0..1 到多个)时,它会正确链接外键并将 ConceptTag 的导航属性添加到 DocumentStyle 对象。我不想要 Tag 对象上的导航属性。

但是,在存储库中调用以下代码时

db.DocumentStyles.Include(d => d.ConceptTag).ToList();

结果查询尝试访问 Tag 表上的属性 DocumentStyle_ID,该属性不存在,也不应该存在。外键是 DocumentStyle 表上的 ConceptTagId。

这个 id 列来自哪里,我该如何摆脱它?

从相关关联的属性窗口:

End1 多重性:* of DocumentStyle
End1 Nav 属性:ConceptTag
End2 多重性:标签之一的零
End2 Nav 属性:{NULL}(属性中的空白)

4

1 回答 1

1

在进一步调查中,它打破了命名风格的惯例。为了解决这个问题,我必须在 OnModelCreating 事件中实现以下规则

builder.Entity<DocumentStyle>().HasOptional(ds => ds.ConceptTag).WithMany(); 

这允许框架知道 Tag 在关系中没有期望的互惠属性,并且它不会尝试在以后的查询中找到 DocumentStyle_Id 属性

于 2011-12-13T19:21:39.823 回答