简体   繁体   English

实体框架中没有外键的一对多关系?

[英]One to many relationship without foreign key in Entity Framework?

The title may be misleading, but right now I can't seem to formulate the right words for what I'm searching for. 标题可能会误导您,但现在我似乎无法为要搜索的内容表达正确的字眼。

As it stands, Entity A has many Entity B, but Entity B will not include an Entity A foreign key. 就目前而言,实体A有许多实体B, 但是实体B将包括实体A外键。

How does that work? 这是如何运作的?

At first, I thought to use the following property in my model. 最初,我想在模型中使用以下属性。

public virtual ICollection<B> Bs { get; set; }

But that's if B has a foreign key to A. Suggestions? 但这就是B是否具有A的外键的建议。 or is this not a thing? 还是这不是一回事? Must I create a separate model just to relate A and B if B does not have the foreign key? 如果B没有外键,是否必须创建一个单独的模型来关联A和B?

I don't know why there can't be an FK on entity B to entity A, but without any sort of referential constraints, there can be no traversal between the two entities (ie you can't extract all B's per given A, and you can't extract the A for a given B). 我不知道为什么在实体B到实体A上没有FK,但是没有任何参照约束,两个实体之间就没有遍历(即,您不能提取给定A的所有B,并且您无法提取给定B的A)。 The easiest way I can tell you is to just add that FK, but if it's not possible, you would need to create another entity that simply acts as the proxy/map for your entity B. BProxy entities should have a 1-1 relationship with B entities. 我可以告诉您的最简单方法是仅添加该FK,但如果不可能,则需要创建另一个实体,该实体仅充当实体B的代理/映射。BProxy实体应与1-1建立关系B实体。

public class BProxy 
{
     [Key]
     public int Id {get; set;}
     [Required]
     public int EntityBId {get; set;}
     public virtual EntityB {get; set;}
     [Required]
     public int EntityAId {get; set;}
     public virtual EntityA {get; set;}
}

Your Entity A would then have a collection of BProxy objects instead of B objects 这样,您的实体A将具有BProxy对象而不是B对象的集合

public virtual ICollection<BProxy> BProxies { get; set; }

This way, you can create queries that traverse the relationships both ways through LINQ. 这样,您可以创建通过LINQ遍历关系的查询。

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

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