You would create the compiled query via:
Func<YourContextType, int, string> query = CompiledQuery.Compile(
(YourContextType context, int id) =>
context.Users.Where(u => u.u_id == id).Select(u => u.u_id)
.SingleOrDefault()
);
You would then use this as:
string resultId = query(context, Id);
As for the performance gain, this may be significant, but it may also be minimal. It really depends on how quick the query is being performed, and how often you can reuse the compiled query. In many cases, using the cmopiled query is actually slower, as the overhead of compilation doesn't make up for the speed gains. You would need to measure to determine if this is worth the effort.
Note that, if you know you only have one unique ID, you can also potentially speed up your original query merely by using FirstOrDefault()
instead of SingleOrDefault()
.