Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of FromExpression in EF 5?

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();
like image 489
LP13 Avatar asked Sep 15 '25 21:09

LP13


1 Answers

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.

like image 79
Ivan Stoev Avatar answered Sep 17 '25 18:09

Ivan Stoev