Use Expression> in Linq on MyEntity..

.net c# entity-framework entity-framework-6 linq

Question

I am trying to simplify a method that returns an IQueryable

A, B and C extend BaseEntity containing a enum that I want to compare. context is a entity framework dbcontext.

Here is a stripped down version of the method:

 return context.MyEntities.Include("A").Include("B").Include("C")
        .Where(x => x.A.MyEnum == MyEnum.<value> && x.B.MyEnum == MyEnum.<value> && x.C.MyEnum == MyEnum.<value>);

I tried to do this:

Func<BaseEntity, bool> equals = x => x.MyEnum == MyEnum.<value>;

return context.MyEntities.Include("A").Include("B").Include("C")
        .Where(x => equals(x.A) && equals(x.B) && equals(x.C));

It compiles but gives a runtime error. For what I understand is that Linq cannot translate the func<> to SQL? So i searched and I found that you need to wrap the func<> in an expression<>, so Linq can compile it and translate it to SQL.

Now I have this:

Expression<Func<BaseEntity, bool>> equals = x => x.MyEnum == MyEnum.<value>;

return context.MyEntities.Include("A").Include("B").Include("C")
        .Where(x => equals(x.A) && equals(x.B) && equals(x.C));

But this doesn't compile: 'Method name expected'. Is there a way to accomplish what i'm trying to do?

1
0
9/30/2019 10:42:45 AM

Accepted Answer

The compile error is because you have to first compile the expression before being able to invoke it.

equals.Compile()(x.A)

But this defeats the purpose of using the expression to begin with.

There is nothing to be simplified in the provided code other than moving the repeated value call into a variable.

var value = MyEnum.<value>;
return context.MyEntities.Include("A").Include("B").Include("C")
    .Where(x => x.A.MyEnum == value && x.B.MyEnum == value && x.C.MyEnum == value);

The attempt to simplify what was shown is not really needed.

1
9/30/2019 12:42:28 PM


Related Questions





Related

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