Entity framework where clause - c#

I am newbie to EF how to use and - or in where clause in the entity framework
HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL attendanceDeviceShutdownTbl =
context.HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL
.FirstOrDefault(x => x.Device_ID.Equals(model.DeviceId) &&
x=>x.Device_Name=model.DeviceName);
the above code will not work but how can I make it works.

Expression lambda has following syntax param => expression. I.e. its like simple method, which have input parameter(s) and body. You define parameters only once and then use them in body of method or lambda:
HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL attendanceDeviceShutdownTbl =
context.HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL.FirstOrDefault(x =>
x.Device_ID.Equals(model.DeviceId) && x.Device_Name == model.DeviceName);
In this case you have single parameter x which goes to anonymous function body. Body is an expression which should return boolean value and (usually) use parameter x. In your case lambda body should be
x.Device_ID.Equals(model.DeviceId) && x.Device_Name == model.DeviceName
Suggested reading: Lambda Expressions (C# Programming Guide). Also note == is a comparison operator. = is an assignment operator. Do not mix up with them.

Related

Surrounding a lambda expression parameter with parentheses

I've been following this tutorial today to learn a bit about the Web API and noticed something - in the tutorial code, there was this line:
var product = products.FirstOrDefault((p) => p.Id == id);
As you can see the parameter "p" is provided in parentheses. Since it's not mandatory having it this way, I'm curious if there's any benefit to doing it that way or if it's just a preference of the developer?
In this case, it's purely developer preference.
Parenthesises are needed when you have more than one parameter. For example:
var singleString = someStrings.Aggregate((current, next) => current + Environment.NewLine + next);
The C# specification explicitly states that (p) => ... can be written as p => ...:
7.15 Anonymous function expressions
...
In an anonymous function with a single, implicitly typed parameter, the parentheses may be omitted from the parameter list. In other words, an anonymous function of the form
( param ) => expr
can be abbreviated to
param => expr
So there is no technical difference whatsoever, only personal preference.

How to use typeof(object).GetMethod() with lambda parameter

How does one use Type.GetMethod() to get a method with lambda parameters? I'm trying to get the Queryable.Any method for a parameter of something like Func, using this:
typeof(Queryable).GetMethod("Any", new Type[]{typeof(Func<ObjType, bool>)})
but it keeps returning null.
There are four things wrong:
There's no such thing as a "lambda parameter". Lambda expressions are often used to provide arguments to methods, but they're converted into delegates or expression trees
You've missed off the first parameter of Queryable.Any - the IQueryable<T>
You're using Func<ObjType, bool> which is a delegate type, instead of Expression<Func<ObjType, bool>> which is an expression tree type
You can't get at generic methods in quite that way, unfortunately.
You want:
var generic = typeof(Queryable).GetMethods()
.Where(m => m.Name == "Any")
.Where(m => m.GetParameters().Length == 2)
.Single();
var constructed = generic.MakeGenericMethod(typeof(ObjType));
That should get you the relevant Any method. It's not clear what you're then going to do with it.

What does '=>' mean?

What does => means? Here's a code snap:
Dispatcher.BeginInvoke((Action)(() => { trace.Add(response); }));
it's lambda expression which is the simplified syntax of anonymous delegate. it reads 'goes to'. equivalent to Dispatcher.BeginInvoke((Action)delegate() { trace.Add(response); });
=> is lambda expression operator which indicate that the code is lambda expression.
( param ) => expr(int x) = > { return x + 1 };
or
param => exprx=> x + 1;>
What is Lambda expression ?
* Lambda expression is replacement of the anonymous method avilable in C#2.0 Lambda
expression can do all thing which can be done by anonymous method.
* Lambda expression are sort and function consist of single line or block of statement.
Read more : Lambda Expressions
=> is an operator called Lambda Operator
It is used for creating a lambda expression
It's the lambda operator =>
It is a lambda operator which reads like "goes to"
This "=>" means the use of lambda expression syntax in C#.
This syntax is available since Visual Studio 2008 in .NET 3.5 (C# 3.0). This is the MSDN official documentation of lambda expression in C#.
The code above is the same as anonymous delegate in already available since C# 2.0
Your code:
Dispatcher.BeginInvoke((Action)(() => { trace.Add(response); }));
is translated into:
Dispatcher.BeginInvoke(new delegate () { trace.Add(response); });
Those two codes essentially have the same semantics.
It's worth noting that a single expression lambda doesn't need the {} around the body, nor does it need a semicolon, so you can simplify your code (slightly) to.
Dispatcher.BeginInvoke((Action)(() => trace.Add(response) ));

Converting Lambda Functions into Lambda Expression

I am trying to combine a multiple selection with a lambda function into an lambda expression. How do I do that? I know the last line is wrong, but giving you an idea of what I mean.
Func<Event, bool> where = null;
if (!string.IsNullOrWhiteSpace(searchToken))
where = q => q.Name.ToUpper().Contains(searchToken.ToUpper());
where += q => q.Hidden = false;
Expression<Func<Event, bool>> where1 = q => where; <-- Erroring
I suspect you want PredicateBuilder. (The source is available on that page.) You'd use it like this:
var predicate = q => !q.Hidden;
if (!string.IsNullOrWhiteSpace(searchToken))
{
predicate = predicate.And(q => q.Name.ToUpper()
.Contains(searchToken.ToUpper());
}
return predicate;
That's assuming you want to "and" the conditions - you never made that clear...
Note that that is not a good way to compare in a case-insensitive way, either. If you could tell us what's going to consume the query (e.g. LINQ to SQL, LINQ to EF) we could suggest a provider-compatible way of performing a case-insensitive query.
Look at http://msdn.microsoft.com/en-us/library/bb882637.aspx. How to use expression trees to build dynamic queries.
AFAIK when using Expression <> like that the expression must be known in compile time, because the compiler then build AST abstract syntax three and stores it as data in your Expression <> instance.

Lambda expression syntax

Is it mandatory that lambda expression need to use when LINQ will be used, or are lambda expressions optional?
In lambda expressions, the sign => is always used. What does it mean?
customers.Where(c => c.City == "London");
Here c => is used but why?
What kind of meaning of using c =>. Please discuss in detail because I don't know lambda.
No, you don't have to use a lambda expression. For example, your Where example could be written as:
private static bool IsLondon(Customer customer)
{
return customer.City == "London";
}
...
var londoners = customers.Where(IsLondon);
That's assuming LINQ to Objects, of course. For LINQ to SQL etc, you'd need to build an expression tree.
As to why "=>" is always used in a lambda expression, that's simply because that's the way the operator is written - it's like asking why "+" is used for addition.
A lambda expression of "c => ..." is effectively giving the lambda expression a parameter called c... in this case generic type inference provides the type of c. The body provides either an action to perform or some calculation to return a value based on c.
A full-blown description of lambda expressions is beyond the scope of this answer. As a blatant plug for my book, however, they're covered in detail in chapter 9 of C# in Depth.
The lambda expression
c => c.City == "London"
is shorthand for something like
bool IsCustomerInLondon(Customer c)
{
return (c.City == "London");
}
It's just a very concise way of writing a simple function that returns a value. It's called an "anonymous function" because it's never assigned a name or a formal definition (the parameter types and the return type are inferred from the context).
(Actually, it's not just shorthand; lambda expressions are related to some other constructs called closures, which are very cool and powerful tools.)
Think about lambdas as anonymous of functions.
I'll try to explain it with following code.
public bool IsLondon(Customer customer)
{
return customer.City == "London";
}
Now we strip down function name and get rid of braces:
public bool Customer customer
return customer.City == "London";
We don't need return type, because compiler is able to deduce type from expression:
customer.City == "London";
In the same manner compiler knows about input type, so we don't need to specify it.
So basically, what we left with is
customer
return customer.City == "London";
And lambda syntax in c# is basically:
(parameter list) => "expression"
You can also write "multi-line" expressions, but then you have to surround your code with curly braces. Also you will need to use "return" statement, like you usually do.
Jon already answered,
but I'd like to add this.
In the example you have given, imagine Linq looping over all customers,
and c is simply a reference to each item in the enumerable:
var result = new List<Customer>();
foreach(var c in customers)
{
if (c.City == "London")
result.Add(c);
}
return result;
It's a variable like any other, it does not have to be a single named one,
but it's just a convention of some sort.
you do not need to use lambda expressions on Lİnq to sql or Entities; here is an alternative way of your code;
you code :
customers.Where(c => c.City == "London");
the other way;
var query = from cs in customers
where cs.City == "London"
select cs;
this is the another way. it is up to you.
Lambda and linq are quite separate. You can use one without using the other (there are parts of linq that depend on lambda expressions, but we want to keep it simple :-) )
A lambda expression is an anonymous
function that can contain expressions
and statements, and can be used to
create delegates or expression tree
types.
This was from MSDN. (http://msdn.microsoft.com/en-us/library/bb397687.aspx )
To make it short (it's much more complex) you can use a lambda expression to make a local function. what you put before the => (in your example the c) will be the parameter of the function. The return type is "discovered" by the C# compiler.
c => c.City == "London" is nearly equivalent to:
delegate (TheObjectTypeOfC c) {
return c.City == London
};
(the difference is that some lambda expression are delegates and also expressions, but please ignore this, you won't need it for some time)
If/when the compiler isn't able to infer the types of the parameters, you can force them: (MyObject p) => p.SomeProperty != null. Here you are telling the compiler that p is a parameter.
While here I showed you what are called "expression lambdas", you can even do "statement lambdas":
p => {
for (int i = 0; i < 10; i++) {
if (p.SomeProperty == 0) {
return true;
}
}
return false;
}
(I won't tell you what are the "behind the scenes" differences between expression lambdas and statement lambdas. If you want to know them, read the msdn page I pointed before)
No it is not necessary at all.
We have two ways to write LINQ queries.
One is query method and other is builder method. You only need to put lambda expression in case of builder method.
For example, if we want to find all those students from some Students object that have more marks than 70.
but we can do this thing in LINQ with following syntax
var data = from p in stdList
where p.marks > 70
select p;
or
var data = stdList.Where(p=>p.marks > 70);
later approach is builder method, in Where function, we are passing lambda expressions.
Lambda expressions are just short cuts of doing things you can always use LINQ queries but if you want to avoid whole query syntax for just applying a simple condition you can just use LINQ builder methods (which asks for lambda expressions) in lambda expressions, you always define some alias and then perform your operation.
As far as => operator is concerned, It works just like assignment operator.
For example:
(p) => p.Gender == “F”
It means “All persons p, such that person’s Gender is F”
In some literature this is called “predicate”. Another literature terminology is “Projection”
(p) => p.Gender ? “F” : “Female”
“Each person p becomes string “Female” if Gender is “F””
This is projection, it uses ternary operator.
Although i explained with very basic examples but i hope this would help you . . . :)

Categories