I am working with a large external data model, that I have no authority over, ie. I can’t change modify the data structure. I need to store this data structure as a field in another record and store this record using EF Core.
My data structure looks something like the following:
public sealed record GameAnalysis
{
public Guid AnalysisID { get; } = Guid.NewGuid();
public string SomeField { get; init; }
public Game Game { get; init; }
}
Where Game
is the external data model that I spoke about. This data model has lists and nested objects:
public class Game
{
public Guid GameID { get; } = Guid.NewGuid();
public string SomeField { get; init; }
public SomeClassWithoutID Stadium { get; init; }
public List<Player> Players { get; init; }
// more fields...
}
I initially tried to make EF Core just set up everything for me, however I got errors that some classes of the nested objects within the Game
class do not contain any ID’s.
I looked into alternative ways of storing this model and even though it is generally not advisable to store data objects as JSON, I do believe that it is the way to go in this case (correct me if I am wrong). I can write a converter using .HasConversion()
, but ideally, I would like to able to index into this data model using LINQ.
In EF Core 7, JSON columns were added, which seem to solve my problem exactly. However, I can’t get it to work. My OnModelCreating
looks like this:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<GameAnalysis>().OwnsOne(
analysis => analysis.Game, ownedNavigationBuilder =>
{
ownedNavigationBuilder.ToJson();
});
}
When using this, I get the same errors as when I just tried to let EF Core take the reins:
Unable to create a ‘DbContext’ of type ”. The exception ‘The entity of type SomeClassWithoutID’ requires a primary key to be defined.’ was thrown while attempting to create an instance.
I can remove the errors one-by-one by adding calls to OwnsOne
and OwnsMany
, but it is quite the hassle to add this to added nested objects within the model. Why is this still needed when using ToJson()
or am I missing something?
Unfortunately there is no way around this, nested types must be acknowledged in the model builder.
EF Core 7.0 – What’s new?
In EF Core, aggregate types are defined using
OwnsOne
andOwnsMany
.