string StrWhere = string.Empty;
StrWhere = " AND ID =5";
String StrQuery ="SELECT * FROM CITY_MAS WHERE + StrWhere";
I want to achieve the same in LINQ. Something along the lines of the following query...
var result = from c in db.CITY_MAS
where + StrWhere
select new { c.ID,c.Name)
You can use Dynamic Linq to dynamically add criteria.
You can either use DynamicLINQ (works also with LINQ to SQL) - see Maarten's post - or you can use the following method:
The ObjectQuery<T>
contains a Where
method that allows to define a string custom predicate. So, your query could be re-written as follows:
var strWhere = "it.ID = 5";
var result = objSet.Where(strWhere);
In the where clause the it
refers to the current object/table - analogous to this
in c#. The objSet
is an ObjectSet<CITY>
(which inherits from ObjectQuery<T>
).
Depending, whether you use an ObjectContext
or a DbContext
the ways to get to objSet
are different:
In an ObjectContext
CITY
already would be an ObjectSet<CITY>
so there is no real additional action needed, so:
var objSet = db.CITY;
Here CITY
is a DbSet<CITY>
and the described override for the Where
method is not available. However, each DbContext
has an underlying ObjectContext
you can use to do some more complex queries. You just have to get to it and then create the ObjectSet
:
// assuming: using System.Data.Entity.Infrastructure;
var var objContext = ((IObjectContextAdapter)ctx).db;
var objSet = objContext.CreateObjectSet<CITY>();
See also this blog post for additional uses. Full documentation on the ObjectSet<T>.Where
method can be found here .
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.