Member Init like Expression for Assignments #797
Replies: 4 comments
-
It's worth having a read of Proposal: shorten lambdas with one argument. Under that proposal, we could have something like: Mapper.CreateMap<Person,PersonDto>()
.ForMember(@.Name, @.Name)
.ForMember(@.Age, @.Age); Whilst not quite the same as your proposal, the key is the comment from a member of the language team, @CyrusNajmabadi:
|
Beta Was this translation helpful? Give feedback.
-
@DavidArno B. That still doesn't help the 2nd use case. Using factories to generate expression for query-able types such as DbSets in EntityFramework. |
Beta Was this translation helpful? Give feedback.
-
In my opinion, this is not something for which adding new syntax would be worth it, especially not syntax that I think looks foreign in C# (angle brackets in C# mean generics, not member initialization). What if instead C# supported converting assignments and blocks to expression trees (#158)? With that, your examples could be: Mapper.CreateMap<Person,PersonDto>((src, dst) => { dst.Name = src.Name; dst.Age = src.Age; }); DbSet<Person>()
.Where(person=> person.Age > 65)
.Select(person => PersonFactoryExpression(newPerson => { newPerson.Name = person.Name; })); |
Beta Was this translation helpful? Give feedback.
-
@svick Having an expression tree for member assignment would exactly solve this. I would add that it should return the instance that we're assigning to so we can have MemberAssignment be an |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Mapping properties in objects to other objects can be made simpler if we were able to assign to an object just like we can initialize a new object.
Now you see code like.
Which is quite verbose.
Instead if we can have something like the following.
MemberAssignementsExpression assignment = <PersonDto>{Name = src.Name, Age = src.Age};
which would allow for
Mapper.CreateMap<Person,PersonDto>((src) => <PersonDto>{Name = src.Name, Age = src.Age});
or
Mapper.CreateMap<Person,PersonDto>(assignment);
Here's a similar request.
#512
Other use cases.
Example:
new string [] {"Joe","Jane"}.Select(s=> new Person{Name = s});
But lets say you can't call new on Person. Instead you have a person factory.
Person PersonFactory() => new Person();
You'd need to do the following.
Or you can change the factory to
which would allow for
The issue with this is that you can't use Expression Queries for Entity Framework or the like.
So using Entity Framework you would do the following.
The select query won't be compiled so the entire person entity will get pulled from the database. Since the query compiler doesn't know that we only need the name.
However, with the assignment expression you'd be able to do the following.
The later should be able to get compiled to sql and only fetch the Name property from the database.
Beta Was this translation helpful? Give feedback.
All reactions