Daniel Brown Daniel Brown - 1 month ago 8x
C# Question

Retrieve list of class from DB using Entity Framework filtered by a computed property?

I have a DB class with the following properties:

public string AwsS3Key { get; set; }
public bool PendingS3Upload => !string.IsNullOrEmpty(AwsS3Key);

I'm trying to pull a list of data from my context by filtering based on the
property. However, I get the following error:

The specified type member 'PendingS3Upload' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

How can I pull data from my table with respect to the "computed" property


You can mark your property with the [NotMapped] attribute. Although you won't be able to Query this at the Database level, only in Memory using ToList() or AsEnumnerable() in some use cases this is out of the question due to large datasets etc.

If you need to query this on the database then assuming you're using SQL Server you can use computed columns.

Computed Column Info

If you want this to be Code First then you'll have to execute some SQL when you initialise the database or migrating.

ALTER TABLE dbo.TableName 
ADD PendingS3Upload AS (CAST(CASE WHEN AwsS3Key <> '' = 1 THEN 1 ELSE 0 END AS BIT))

Then change your Class Property to

public bool PendingS3Upload { get; private set;}

(I can't remember if the private set will work)