I am trying to understand whats the use of new FromExpression
extension method introduced in EF 5 since there are already few different ways you can query entity
Using FromExpression
:
var q = DBContext.Set<MyUser>()
.Include(x => x.UserRoles)
.ThenInclude(y => y.Role)
.Where(x => x.LoginName == loginName);
return await DBContext.FromExpression<MyUser>(() => q).SingleOrDefaultAsync();
Without using FromExpression
:
my old syntax queries using single line
var user = DBContext.Set<MyUser>()
.Include(x => x.UserRoles)
.ThenInclude(y => y.Role)
.Where(x => x.LoginName == loginName)
.SingleOrDefaultAsync();
Or I can also make use of extension method.
public static IQueryable<MyUser> FindUser(this IQueryable<MyUser> source, string loginName)
{
return source
.Include(x => x.UserRoles).ThenInclude(y => y.Role)
.Where(x => x.LoginName == loginName)
}
var user = DBContext.Set<MyUser>()
.FindUser(loginName)
.SingleOrDefaultAsync();
All these scenarios do not need FromExpression
(although it sort of works with them).
The main (and probably the only) usage of that method is for Mapping a queryable function to a table-valued function as explained in the documentation link with examples, so I'm not going to copy/paste everything written there. The method is essential for that type of mapping since it doesn't support the scalar function mapping with HasTranslation
.
Shortly, use the "old syntax" for regular LINQ to entities query scenarios, and FromExpression
only for exposing TVF mapped queryable function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With