Henrik Stenbæk
Henrik Stenbæk

Reputation: 4082

Unable to query with linq on a class with an Owned Entity

I have a entity like this, with a property that is mapped as an owned entity:

public class Foo
{
    public int Id { get; set; }

    public DateTimeWithTimeZone DoneAt { get; set; }
} 

public class DateTimeWithTimeZone
{
    public DateTimeOffset Time { get; set; }

    public string TimeZone { get; set; }
}

And the database configuration looking like this:

public void Configure(EntityTypeBuilder<Foo> builder)
{
    builder.HasKey(x => x.Id);

    builder.OwnsOne(x => x.DoneAt, y =>
    {
        y.WithOwner();
        y.Property(z => z.Time).HasColumnName("DoneAt");
        y.Property(z => z.TimeZone).HasColumnName("DoneAtTimeZone");
    });
}

I can insert a Foo entity into the datbase with EF and get the list of Foos back for the database:

var list = apiDbContext.Foos.ToList();
var list = apiDbContext.Foos.FirstOrDefault(x => x.Id == 1122);

But when I what to query for LastOrDefault:

var p = apiDbContext.Foos.LastOrDefault(x => x.Id == 1122);

I'm getting this error:

System.InvalidOperationException: 'The LINQ expression 'DbSet<Prescription>
    .Where(p => p.Id == 1122)
    .Select(p => (IncludeExpression(
        EF.Property<DateTimeWithTimeZone>(p, "DoneAt"), DoneAt)
    ))
    .Last()' could not be translated. 
Either rewrite the query in a form that can be translated, or 
switch to client evaluation explicitly 
by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().

Upvotes: 0

Views: 279

Answers (1)

Henrik Stenb&#230;k
Henrik Stenb&#230;k

Reputation: 4082

The reason was that when using .LastOrDefault() one need to specify OrderBy.

This is working:

var p = apiDbContext.Foos.OrderBy(x => x.Id).LastOrDefault(x => x.Filter == 1122);

Upvotes: 2

Related Questions