I have a class that is an entity in the DB and has a owned entity:
public class EntityOne
{
public int Id { get; set; }
public OwnedEntity OwnedEntity { get; set; }
}
I have the owned entity with a list with the type of another persisted entity:
public class OwnedEntity
{
public int Id { get; set; }
public List<EntityTwo> EntityTwo { get; set; }
}
And here is the EntityTwo:
public class EntityTwo
{
public int Id { get; set; }
// all other properties
}
I need to create the relationship between EntityOne and EntityTwo as a many to one, but the property navigation is in my owned entity. How can I do that?
I tried to create a property navigation of my owned entity like this:
public class EntityTwo
{
public int Id { get; set; }
public OwnedEntity OwnedEntity { get; set; }
public int OwnedEntityId { get; set; }
// all other properties
}
And the map:
builder.HasOne(prop => prop.OwnedEntity)
.WithMany(prop => prop.EntityTwo)
.HasForeignKey(prop => prop.OwnedEntityId);
But I got an error because ef tries to make my owned entity as a entity table.
Then, I tried to reference the parent entity:
public class EntityTwo
{
public int Id { get; set; }
public EntityOne EntityOne { get; set; }
public int EntityOneId { get; set; }
// all other properties
}
And mapping with inner properties:
builder.HasOne(prop => prop.EntityOne.OwnedEntity)
.WithMany(prop => prop.EntityTwo)
.HasForeignKey(prop => prop.EntityOne.OwnedEntityId);
But it didn't work and i got another ef error:
Error: The expression 'prop => prop.EntityOne.OwnedEntity' is not a valid member access expression. The expression should represent a simple property or field access: 't => t.MyProperty'. (Parameter 'memberAccessExpression')
So, is there any way to create this relationship?
For those who want to know how I solved it, I did it all inside the map configuration of the entity one, using the OwnsMany. First, I changed the one-to-many reference of EntityTwo to the OwnedEntity:
Then, i made this map (builder of the EntityOne):
That's it.