Home > database >  Using EF Core EntityTypeBuilder with nested/complex properties
Using EF Core EntityTypeBuilder with nested/complex properties

Time:10-21

I have something like the TrackingMetrics entity below (with more logic and methods in practice), but I'm having trouble figuring out the syntax for mapping this to the database using entity framework.

At the end of the day, I want to track the response to each metric as a column, but setting up a complex grandchild like relationship with EF is giving me trouble.

I have one of several EntityTypeBuilder configurations I've tried to get this to work to no avail. Anyone done something like this before?

public class TrackingMetrics 
{
    public Guid Id { get; set; }
    public PrimaryMetrics PrimaryMetrics { get; private set; }
}

public class PrimaryMetrics : ValueObject
{
    public MetricOne MetricOne { get; set; }
    public MetricTwo MetricOne { get; set; }

    public PrimaryMetrics()
    {
        MetricOne.Set("Unanswered");
        MetricTwo.Set("Unanswered");
    }
}


public class MetricOne : ValueObject, IMetric
{
    public Response Response { get; private set; }
    public void Set(Response response)
    {
        Response = response;
    }
}


public class MetricTwo : ValueObject, IMetric
{
    public Response Response { get; private set; }
    public void Set(Response response)
    {
        Response = response;
    }
}

public class Response : ValueObject
{
    public string Value { get; set; }
}

public sealed class PrimaryMetricsConfiguration : IEntityTypeConfiguration<PrimaryMetrics>
{
    public void Configure(EntityTypeBuilder<PrimaryMetrics> builder)
    {        
        builder.OwnsOne(x => x.PrimaryMetrics, opts =>
        {
            opts.Property(x => x.MetricOne.Response)
                .HasConversion(x => x.Value, x => new Response(x))
                .HasColumnName("primary_metrics_metric_one_response");
            opts.Property(x => x.MetricTwo.Response)
                .HasConversion(x => x.Value, x => new Response(x))
                .HasColumnName("primary_metrics_metric_two_response");
        }).Navigation(x => x.PrimaryMetrics)
            .IsRequired();
    }
}

This is the actual error I get:

The expression 'x => x.MetricOne.Response' is not a valid member access expression. The expression should represent a simple property or field access: 't => t.MyProperty'. (Parameter 'memberAccessExpression')

CodePudding user response:

can't format in comments so here it is again:

builder.OwnsOne(root => root.Address1, address =>
            {
                address.OwnsOne(a => a.SubAddress, subAddress =>
                {
                    subAddress.OwnsOne(it => it.SubSubAddress);
                });
            });
  • Related