I have googled a lot to understand the lambda expressions in c#. Though people have given a handful of information, I couldn't understand what it is. Can any one explain me with the following code. This code can give me the understanding, since it is "my" context.
context.Authors.AddOrUpdate(x => x.Id,
new Author() { Id = 1, Name = "Jane Austen" },
new Author() { Id = 2, Name = "Charles Dickens" },
new Author() { Id = 3, Name = "Miguel de Cervantes" }
);
Why it is not "x=>x" ?
is a shorthand for
which is a function that takes x as a parameter and returns x, while
is a shorthand for
This basically means that the
AddOrUpdate
function needs to know how to get the Id of the entities it's adding or updating, you can think of lambdas as a compact way of defining functions, in most cases you can actually define a function:and use the function in place of the lambda:
Inside the AddOrUpdate function, it will run the GetAuthorId passing an Author as a parameter whenever it wants to find an Author's Id
--EDIT--
As correctly noted in the comments, what I just said is true for
Func<>
, but is NOT true forExpression<Func<>>
you can read a little about the difference hereSimply stated, it's because the method is expecting to receive an expression that represents the semantic key for
Authors
.Think of it like this - if you passed in
x => x
, you would be trying to perform the following operation:Author
objects.Whereas when you pass in
x => x.Id
, you're saying:To understand why, it may help you note the method takes an
Expression<Func<TEntity,Object>>
. This parameter type is often use to perform operations upon an arbitrary property, likeAddOrUpdate
is doing here.Here's an example of a method would takes a expression and prints out the member name of the property. There's a lot more power here, but this should atleast help explain why
AddOrUpdate()
takes the parameters it does.Because the function wants sometime to uniquely identify each object. In this case the ID of the object.
If the ID exists, an update is performed. If the ID doesn't exist, an insert is performed.