Reputation: 5621
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get; set; }
}
var joe = new Person {
FirstName = "Joe",
LastName = "Smith",
//The following line produces the error:
//The Name FirstName does not exist in the current context
FullName = Firstname + " " + LastName
}
If I try to do this in C#, it will not allow me to reference the other properties.
If I do it this way:
var joe = new Person ()
joe.FirstName = "Joe";
joe.LastName = "Smith";
joe.FullName = Firstname + " " + LastName;
All is fine.
My understanding is that with Object Literal instantiation, the compiler turns everything into the second example at compile time.
However, in Linq to Entity, we have to use Object Literals in Object Instantiation like so:
List<PersonDTO> people = dbContext.Person.Where(x => x.IsAlive)
.Select(y => new PersonDTO
{
FirstName = y.FirstName,
LastName = y.LastName,
FullName = ???
}
I know I can reference y.FirstName + " " y.LastName
but that creates extra code in the resulting SQL query.
And while this is a simple example, I'm working with much larger and more complex data sets.
So the question is:
Is there a way to concatenate properties together in an Object Literal Instantiation?
If not, can I pass y
into an object constructor somehow?
If not, what is the best way to do something like this?
Upvotes: 0
Views: 68
Reputation: 39346
My recommendation in this case is use a NotMapped property in your Person
entity:
public class Person
{
//..
[NotMapped]
public string FullName
get
{
return FirstName + " " + LastName;
}
}
Upvotes: 2
Reputation: 3371
If your looking for a way to create a FullName property in your class, then the best way to do this is to create a class file in your project that contains a partial class to Person.
public partial class Person
{
public string FullName
get
{
return FirstName + " " + LastName
}
}
Upvotes: 0