Reputation: 1054
I want to define a one to many relationship on an owned type.
Here in my example,
InboundRequest: principal entity
RequestHistory: owned type
RequestHistoryEntry : Dependency entity
public class InboundRequest : IAggregateRoot
{
public int Id { get; private set; }
public RequestHistory History { get; private set; }
}
public class RequestHistory
{
public IList<RequestHistoryEntry> HistoryEntries { get; set; }
}
public class RequestHistoryEntry
{
public RequestState State { get; private set; }
public DateTime Timestamp { get; private set; }
public int Id { get; set; }
}
builder.Entity<InboundRequest>().OwnsOne(x => x.History);
Unfortunately EF Core gives me the following error:
The relationship from 'RequestHistoryEntry' to 'InboundRequest.History#RequestHistory.HistoryEntries' is not supported because the owned entity type 'InboundRequest.History#RequestHistory' cannot be on the principal side.
Is there a way to have a one to many relationship between an owned type and a list of dependencies?
Upvotes: 13
Views: 1753
Reputation: 86
The only way to have a one to many relationship with owned types is if the owned entity is on the many side of the relationship, in which case ef core will map it to a separate table by convention. What you are attempting is per se not possible by design. However, in your particular case, why don't you get rid of RequestHistory
altogether and make the list of RequestHistoryEntry
as a collection of owned type to your InboundRequest
as follows:
public class InboundRequest : IAggregateRoot
{
public int Id { get; private set; }
public IList<RequestHistoryEntry> HistoryEntries { get; set; }
}
public class RequestHistoryEntry
{
public RequestState State { get; private set; }
public DateTime Timestamp { get; private set; }
public int Id { get; set; }
}
builder.Entity<InboundRequest>().OwnsMany(x => x.HistoryEntries);
That should get rid of the error as well as achieve your desired relationship to your dependent entity.
Upvotes: 1
Reputation: 21
You cannot set a list of objects as a owned type, because the columns of your History table are added to the InboundRequest table. The column count of the table must be fixed and not dynamic.
If you write the following:
public RequestHistoryEntry HistoryEntries { get; set; }
Then your InboundRequest table looks like that (or similar):
| Id | RequestHistory_State | RequestHistory_Timestamp | RequestHistory_Id |
If you are using a List of RequestHistoryEntry, then the column count is not clear. Therfore you have to use a separate table for it.
Upvotes: 0