2

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);
Marek Karbarz
  • 28,956
  • 6
  • 53
  • 73
Suraj Shrestha
  • 106
  • 3
  • 7

2 Answers2

4

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)

sehe
  • 374,641
  • 47
  • 450
  • 633
  • I'd suggest this as the answer, since LINQ itself does not support dynamic objects in expressions (hence the error message). – sukru Apr 11 '11 at 06:34
  • I have not tried this solution yet. Even it this works, I am not much comfortable. It is like going back to old sql string (ado.net). – Suraj Shrestha Apr 11 '11 at 19:00
  • It will be anyway, Suraj. As long as you are using dynamic, it is an odd thing to complain about latebinding. Also, don't forget, you _only_ have to use it at the latebound step, all the rest can be strongtype like we all love to – sehe Apr 11 '11 at 21:14
2

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();
Community
  • 1
  • 1
drzaus
  • 24,171
  • 16
  • 142
  • 201