简体   繁体   中英

Entity Framework Core, emitting/generating expression in select

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...

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 => 
    {
        builder.HasName("nvl");
    });
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM