Egi Egi - 24 days ago 6
C# Question

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.

I have my self referencing table where I have my entity and a reference to the parent item:

MyEntity(Id, Name, 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.

MyView(EntityId, EntityRootId)

I made a virtual property in MyEntity to directly traverse to the root element over the view so to say.
It worked as long as I hade a step in between, where I gave the view its own entity (MyEntityRoot).

MyEntity > MyEntityRoot > MyEntity

Now I want to remove that indirection and go directly from
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")
)

Egi Egi
Answer

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.