Suraj Shrestha
Suraj Shrestha

Reputation: 106

An expression tree may not contain a dynamic operation

I get this error if I try to pass dynamic type value into entity framework linq query.

dynamic sname = "suraj";    // even object, var
AppUser appUser = Ctx.AppUsers.First(u => u.Name == sname);

If i try to store the value first in string and use it, I get "object reference error".

var name = "suraj";
string sname = new string(((string)name).ToCharArray());

AppUser appUser = Ctx.AppUsers.First(u => u.Name == sname);

Upvotes: 2

Views: 3717

Answers (2)

drzaus
drzaus

Reputation: 24994

Similar to @Suraj's answer, since dynamic is apparently okay in a delegate (Func) but not an Expression, then you can convert the delegate into an expression:

dynamic config = JsonConvert.DeserializeObject(configJsonString);
var typeName = config.type.ToString(); // clause expects a string, just separating it out for readability

// the guts of your clause --
// we'll turn this into an expression with o => wrapper(o)
Func<TEntity, bool> wrapper = (n => n.Name == typeName);

// wrap to expression and use as regular clause
var expectedType = repository.Where(o => wrapper(o)).FirstOrDefault();

Upvotes: 2

sehe
sehe

Reputation: 392911

Have a look at DLINQ which allows you to do stuff like:

var query =
    db.Customers.
    Where("City = @0 and Orders.Count >= @1", "London", 10).
    OrderBy("CompanyName").
    Select("new(CompanyName as Name, Phone)");

Note that expressions in the query are strings that could have been dynamically constructed at run-time.

The library has some very very nice goodies, including implicit conversion to Expression Trees, that you will be able to smoothly integrate into your existing expression tree.

(DLINQ is pretty amazing when you think off how it was writting around 2006 and still is right on the front of C# technological advancements; Download included in the \LinqSamples\DynamicQuery directory here)

Upvotes: 4

Related Questions