在实体框架中创建关联?
我有一个数据库,其中的表没有主键/外键。这个数据库是第三方的,所以我真的不想编辑底层数据库结构。相反,我创建了一个 EF 模型,其中包含我想要使用的表...现在我想在模型级别定义不同实体之间的关联。例如,我有一个 Person 对象和一个 Demographic 对象,它们共享一个完全相同的 people_code_id 列...但我似乎不知道如何让这个关联显示出来,然后如何能够访问这些附加列是通过 EntityDataSource 实现的吗?
I have a database in which the tables do not have primary/foreign keys. This database is third party, so I don't really want to edit the underlying database structure. Instead, I've created an EF model which has the tables I want to work with...now I'd like to at the model level define the associations between different entities. For example, I have a Person object and a Demographic object, they share a people_code_id column which will be identical...but I can't seem to figure out how to get this association to show up and then how to be able to access these additional columns via EntityDataSource?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您必须在实体模型中定义主键。每个实体都必须有主键,否则您将无法定义关系并且所有实体都将变为只读。一旦定义了主键并且相关表包含外键属性(只是相关实体的 PK 的 id),您就可以手动创建关联。 这里< /a> 是如何做到这一点的一般方法。即使您没有在数据库中定义关系,它也应该可以工作。
First you must define primary keys in your entity model. Each entity must have primary key or you will not be able to define relation as well as all your entities become read-only. Once you have primary keys defined and your related tables contains foreign key properties (just id of related entity's PK) you can create associations manually. Here is general approach how to do that. It should work even if you don't have relations defined in DB.
除非在数据库架构中定义了关联,否则 EF 不会显示关联。您仍然可以使用键进行连接,就像在普通 SQL 中一样,以匹配键及其引用。
如果您向数据库模式添加了约束,则不需要更改表本身,并且除非您已经遇到约束问题,否则这应该毫不费力。
EF won't show associations unless they are defined in the database schema. You can still used the keys to do joins like you would in plain SQL to match the keys and their references.
I you added constraints to the DB schema, you wouldn't need to change the tables themselves and it should be effortless unless you already have constraint problems.