简体   繁体   English

手动实体框架关联

[英]Manual Entity Framework association

I have the following tables: 我有以下表格:

Table Group (
   id INT PK,
   year INT PK,
   name VARCHAR
)

Table Person (
    id PK,
    GroupID INT,
    name VARCHAR
)

The database does not have foreign keys defined so I want to create a manual association from the Person tables GroupID to the Group tables id . 该数据库没有定义外键,因此我想创建一个从Person表GroupID到Group表id的手动关联。

To do this I right click Person and Add an association. 为此,我右键单击“人”并添加关联。 I create a Many to One association and everything works. 我创建了一个多对一关联,并且一切正常。 The problem is when I go to add the mapping. 问题是当我去添加映射时。 Because the Group table has two primary keys entity framework was something from the Person table to map to the year key. 因为Group表具有两个主键,所以实体框架是从Person表中映射到year键的。

What do I need to do to create the association? 创建关联需要做什么?

You cannot create such association because EF follows same rules as database. 您无法创建此类关联,因为EF遵循与数据库相同的规则。 All PK columns from principal entity must exists as FK columns in dependent entity. 来自主体实体的所有PK列必须作为FK列存在于从属实体中。

The only way can be some database view selecting distinct Groups with Id and Name and mapped as read only entity and build navigation between those two. 唯一的方法可以是某些数据库视图选择具有ID和Name的不同组,并将其映射为只读实体,并在这两者之间建立导航。 I didn't try it but I guess it should work. 我没有尝试过,但我认为它应该可以工作。 It will have its own disadvantages because you will have two completely unrelated entities for group and the entity related to person will not accept any modification (without mapping custom SQL commands or stored procedures to insert, updated and delete operations). 这将有其自身的缺点,因为您将有两个完全不相关的组实体,而与人相关的实体将不接受任何修改(不映射自定义SQL命令或存储过程以进行插入,更新和删除操作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM