简体   繁体   English

在实体框架6流畅的api中的视图上映射多对一关系

[英]Mapping a many to one relationship over a view in entity framework 6 fluent api

I have an issue with a hierarchical setup here, and I can't get my head around how to configure that correctly with entity framework fluentapi, or if it is even possible. 我在这里遇到层次结构设置的问题,我无法理解如何使用实体框架fluentapi正确配置它,甚至可能。

I have my self referencing table where I have my entity and a reference to the parent item: 我有自己的自引用表,其中有我的实体和对父项的引用:

MyEntity(Id, Name, ParentId) MyEntity(ID,名称,ParentId)

I get my tree that I can traverse, that works fine. 我得到了我可以穿过的树,效果很好。 I made a view, where I have for each MyEntityId the MyEntityId of the root entity. 我做了一个视图,其中每个MyEntityId都有根实体的MyEntityId。

MyView(EntityId, EntityRootId) MyView(EntityId,EntityRootId)

I made a virtual property in MyEntity to directly traverse to the root element over the view so to say. 可以这么说,我在MyEntity中创建了一个虚拟属性,可以直接遍历视图中的根元素。 It worked as long as I hade a step in between, where I gave the view its own entity (MyEntityRoot). 只要我之间有一个步骤,它就起作用了,在该步骤中,我给视图提供了自己的实体(MyEntityRoot)。

MyEntity > MyEntityRoot > MyEntity MyEntity> MyEntityRoot> MyEntity

Now I want to remove that indirection and go directly from MyEntity > MyEntity 现在,我想删除该间接关系,然后直接从MyEntity> MyEntity转到

Basically it works like two one to one relationships, but I want it to behave as a many to one relationship with a mapping table in between. 基本上,它就像两个一对一的关系一样工作,但是我希望它表现为与它们之间的映射表多对一的关系。 The mapping table is readonly and only for easy navigation. 映射表是只读的,仅用于轻松导航。

Is it even possible? 可能吗 Or do I have to stick to the entity inbetween even though I don't want it there? 还是我不想在实体之间坚持下去?

what would it look like? 它会是什么样子? I tried something like that, but that does not work. 我尝试过类似的方法,但这不起作用。

modelBuilder
    .Entity<MyEntity>()
    .HasRequired(e => e.Root)
    .WithMany()
    .Map(m => 
        m.ToTable("MyView");
        m.MapKey("EntityRootId")
    )

Well, I guess it is not possible. 好吧,我想这是不可能的。

I solved it by handling it as a many to many relationship. 我通过处理多对多关系解决了它。 The view works as the associative table. 该视图用作关联表。

The only issue that is left is that I have to access it like MyEntity.Roots.First() instead of MyEntity.Root, although there is always exactly one element. 剩下的唯一问题是我必须像MyEntity.Roots.First()一样访问它,而不是MyEntity.Root,尽管始终只有一个元素。

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

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