Reputation: 8977
Files
.Name
, CreatedDate
, etc.FileBytes
.So our model looks similar to:
public class FileEntity
{
public string Name { get; set; }
public DateTime CreatedDate { get; set; }
public byte[] FileBytes { get; set; }
// many other fields, most of which we'd like to use
}
FileBytes
is null
, not anything about the bytes themselves.FileHasBytes
that is a bool
.How can I, using EF6, define a field on my model class that will be consistently projected, based on another field in the table, without pulling the full contents of that field?
Upvotes: 5
Views: 152
Reputation: 11396
With the current version of EF6 you can't do exactly what you are after.
There are other alternatives, but with all of them you'd have to make compromises on the goals stated above. Such as either using a new projected type with the computed property, or not querying on the computed value and be explicit on the condition instead, etc.
However, using something like DelegateDecompiler it might be possible to have the model and query just as you are expecting.
Something along the lines of:
[Computed]
public bool HasFileBytes
{
get { return FileBytes != null; }
}
And in your query you'd use the .Decompile()
call to get that translated:
var query = ctx.Files
.Where(x => x.HasFileBytes)
.Decompile();
Using Linq.Translations could be another similar alternative.
source: http://www.daveaglick.com/posts/computed-properties-and-entity-framework
Upvotes: 2
Reputation: 1247
This is not ideal but I think you can add a static property that returns QueryExpression like
public static Expression<Func<FileEntity,bool>> FileHasBytes
{
get { return ((c)=> c.FileBytes != null && SqlFunctions.DataLength(c.FileBytes)>0)
}
I have not tried this code, so take this with grain of salt, so try and test it thoroughly.
I have used some thing like this using Dynamic.linq some time ago, but not tried it lately
dbContext.FileEntities.Where("FileHasBytes == true"),
Upvotes: 1