我正在开发一个应用程序,我需要为模型中的每个实体存储0,1个或多个注释以及0,1个或多个附件。
为此,我正在考虑开发一个包含以下列的实体:
id [pk] tableName tableId comment
1 'Order' 123 'This is some comment'
2 'Order' 123 'This is antoher comment'
3 'Order' 124 'This is comment to another order'
4 'Customer' 56 'This is comment linked to a customer'
因此,我可以只使用tableName和tableId字段将此通用实体中的注释链接到每个实体,而不是向每个实体添加commentId。
现在......当使用实体框架导航属性时,我并没有真正看到从我的Invoice或Customer表导航到正确记录的内置方式。这可以通过以某种方式制作您自己的导航属性来实现吗?
如果不是.....还有另一种方法可以达到类似的结果。
谢谢!
答案 0 :(得分:0)
在我看来,你正在描述一个正常的一对多关系。您应该将主实体存储在1个表中,将链接的实体存储在另一个表中:
id entityname entityProperty
1 FirstEntity Im a property
2 SecondEntity Me too
id entityid comment
1 1 This is a comment
2 1 This is also a comment
3 2 This might be a comment
id entityid attachment
1 1 This is an attachment
2 2 This is also an attachment
3 2 This might be an attachment
如果您打算先使用代码,可能需要查看以下内容: http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx
答案 1 :(得分:0)
您将遇到的最大问题是,您需要一个FK引用回到表中,以获取此评论的记录。因此,您需要一堆可为空的属性,这些属性指向可存储在此处的每个表的相应记录。这不是最好的解决方案,因为每个新表都需要在Comment表上添加一个新列(但如果您想使用导航属性,这是一个选项)。因此,我不认为EF导航属性会起作用,因为您无法使用相同的2个FK指向多个表。
我能想到的唯一另一件事就是不那么好。您必须手动构建查询并创建未映射到每个父级的ICollection。然后你必须自己建立评论列表。但是,这不是太难,只是更烦人。