简体   繁体   English

实体框架一对一关系?

[英]Entity Framework One to One relation?

I've generated my tables from my diagram : 我已经从图表中生成了表格:

Database schema But I dunno why, EF will generate this in the Origin model: 数据库模式但是我不知道为什么,EF会在Origin模型中生成它:

public virtual ICollection<Container> Containers { get; set; }

In the Container model : 在容器模型中:

public int OriginID { get; set; }
public virtual Origin Origin { get; set; }

and in the context : 在上下文中:

modelBuilder.Entity<Origin>()
            .HasMany(e => e.Containers)
            .WithRequired(e => e.Origin)
            .WillCascadeOnDelete(false);

But a Container Object CAN ONLY have one Origin object. 但是一个容器对象只能有一个原始对象。

How can I remove the collection to have only one instance of my object in the origin object ? 如何删除集合,使原始对象中只有一个对象实例?

Because actually my Restier service is retrieving me origins objects with a collection of only ONE container. 因为实际上我的Restier服务正在检索仅包含一个容器的集合的原始对象。

So the collection is totally useless. 因此,收集完全没有用。

Do you guys have any idea? 你们有什么主意吗?

Thank you very much 非常感谢你

Because origins could well be related to a lot of containers - they don't know it. 因为起源很可能与许多容器有关-他们不知道。 What you have is a one(origin) to many(container). 您拥有的是一个(起源)于多个(容器)。 Say I have origin with ID 1 and container A with originID 1. What would prevent me from adding container B with the same originID? 假设我的原产地ID为1,容器A的原点ID为1。是什么使我无法添加具有相同原点ID的容器B? If you insist on a 1-to-1 relation, try adding keys to both models - origin should know it's only related to the one container and vice-versa. 如果您坚持一对一关系,请尝试向两个模型添加键-原点应该知道它仅与一个容器相关,反之亦然。

TD;DR: Add ContainerID to the Origin table. TD; DR:将ContainerID添加到Origin表。

i think that the best way to add a one-to-one relation is have a primary key that is also a foreign key. 我认为添加一对一关系的最佳方法是拥有一个主键,这也是一个外键。

( the Origin Id should reference the Container id) (来源ID应引用容器ID)

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

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