-
Notifications
You must be signed in to change notification settings - Fork 3.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Static value objects causes InvalidOperationException when using the value object instead of primitive type in predicates #29405
Comments
Note for triage: we should consider a better exception message in this case when the property is a shadow property. @johannbrink The specific exception being thrown is discussed in #28154. However, the underlying issue is that the In this case, I would recommend using a value converter to map the public class PostConfiguration: IEntityTypeConfiguration<Post>
{
public void Configure(EntityTypeBuilder<Post> builder)
{
builder.Property(e => e.Status).HasConversion<StatusConverter>();
}
private class StatusConverter : ValueConverter<Status, string>
{
public StatusConverter()
: base(
v => v.Name,
v => v == "Active" ? Status.Active : Status.Inactive,
new RelationalConverterMappingHints(size: 20, unicode: false))
{
}
}
} Natural queries using the value object will now translate: var posts2 = db.Posts
.Where(p => p.Status.Equals(Status.Active)).ToList(); SELECT "p"."PostId", "p"."BlogId", "p"."Content", "p"."Status", "p"."Title"
FROM "Posts" AS "p"
WHERE "p"."Status" = 'Active' Querying into the value object like this won't work: var posts1 = db.Posts
.Where(p => p.Status.Name.Equals(Status.Active.Name)).ToList(); This is because the value object contents is opaque to EF and so EF cannot create a translation. It might be possible to do this if #10434 is implemented. Original mapping as an entity type:
New mapping as a property:
|
Filed #29442 to track creating a better exception message. |
Thanks @ajcvickers, that was very helpful. I will add the value converter to my projects and update my queries to a more natural form. |
The following line of code causes an InvalidOperationException:
db.Posts.Where(p => p.Status.Equals(Status.Active))
Status is of type ValueObject that implements IComparable and IComparable
Github repo with simplified example code: https://github.com/johannbrink/EFCoreValueObjectPredicateExample
Steps to reproduce
Console output with stack trace
EF Core version: 6.0.10
Database provider: Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Sqlite
Target framework: (e.g. .NET 6.0)
Operating system: All
IDE: All
The text was updated successfully, but these errors were encountered: