Entity Framework Core, emitting/generating expression in select

c# entity-framework-core


I'm using Entity Framework Core in .Net Core 2.2, with the recently released Oracle.EntityFrameworkCore library.

I'd like to be able to generate a query like this...

select nvl(nullablecolumn, 'N') from table;

I think I'm right in saying that I can't do this, at least not out of the box... I can however do something similar, using something like this (but then if I end up writing this, why not write actual SQL and skip Entity Framework???)...

from row in table 
select new { somedata = row.nullablecolumn ?? "N" };

The above linq query gets me the same sort of answer as I'm after... question is, can I do some expression tree magic to get the same result?

For example, this question looks like it generates an expression tree for a "like" query, so how would I generate an expression tree (or modify the existing expression tree) to make the select side of the statement emit nvl()?

This would be useful where you have Entity Framework Value Conversions...

Bonus points (if I could give bonus points) if you can give me a clue on how to create an expression tree to manipulate the where side of the query... AutoMapper manages this somehow with "Projections"?

Any thoughts/pointers would be greatly appreciated...

9/6/2019 6:06:50 PM

Popular Answer

To translate your own method invocation to proper SQL function you can use HasDbFunction from docs.

You have to define own static method as

public static class OracleDbFunction
    public static string Nvl(string string1, string replace_with) => throw new NotImplementedException(); // You can provide matching in-memory implementation for client-side evaluation of query if needed

register it in your DbContext

protected overridevoid OnModelCreating(ModelBuilder modelBuilder)
    modelBuilder.HasDbFunction(typeof(OracleDbFunction).GetMethod(nameof(OracleDbFunctionExtensions.Nvl, builder => 

and use it in your Where expression as

.Where(i => OracleDbFunction.Nvl(i.nullablecolumn, "N") == "N")

You can also use attribute DbFunctionAttribute on OracleDbFunctionExtensions.Nvl to avoid registering it in OnModelCreating

9/7/2019 7:24:25 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow