Reputation: 779
I am working with asp.net mvc 4 and entity framework code-first approach. I have the following entity model
public class User
{
public virtual int Id { get; set; }
public virtual String FirstName { get; set; }
public virtual String MiddleName { get; set; }
public virtual String LastName { get; set; }
}
For the user list view page I need to show Full Name, I am trying to create a get only property in user model like
public virtual String FullName{
get{
return FirstName + " " + MiddleName + " " + LastName;
}
}
But I am not sure if it will work, besides I also don't want entity framework to map this to a database column.
Can I use similar get only property generated from other properties for only view? Can any one can give me any suggestion on what to do??
Upvotes: 1
Views: 3588
Reputation: 4379
Depending on how you are configuring your Domain Entities, via DataAnnotations or EntityConfigurationType classes, you could either use the [NotMapped] DataAnnotation
public class User
{
public virtual int Id { get; set; }
public virtual String FirstName { get; set; }
public virtual String MiddleName { get; set; }
public virtual String LastName { get; set; }
[NotMapped]
public virtual String FullName
{
get{
return FirstName + " " + MiddleName + " " + LastName;
}
}
}
or in a specific class that implements EntityTypeConfiguration, you can set the property to be ignored by EntityFramework like so and then add it to your contexts configurations collection in the OnModelCreating event:
public class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
Ignore(u=>u.FullName);
}
}
Upvotes: 7
Reputation: 37543
If you're putting this property in your model because you need to display it in the view then you're missing the point of MVC in the first place. The model is supposed to be constructed in a manner that properly describes the data to be used. This may or may not be an entity model that mirrors your data base structure. It also may or may not be exactly what the view is looking for.
In this case, you have to ask yourself why you're adding this to your model and if it's simply code bloat. You already have the information necessary within the model to create this particular string. If the view needs to display this information in a particular format, then it belongs in the view. If, however, you know you'll need this exact logic in several other places in the exact same format each and every time, then it could be argued that this property belongs in the view because it is a more globally descriptive implementation of the data in question.
Given your specific example, this read only property is simply code bloat in my opinion. Something of this nature belongs in the view using this data.
Upvotes: 0