views:

28

answers:

1

Hi All, Im just wondering how you go about creating dynamic properties on entities that generated from a database generated model.

For example I have a UserInformation table. In that table it has basic information on the user (well derr) like user name, address details etc etc. I want to add a readonly property that concatenates the user's Name, Address details and Phone Number into one string that I can output to a view. Any ideas on how i would go about creating this dynamic property. This is just a simple example, i am wanting to do some more complex calculating and concatenating.

Thanks

+1  A: 

There are a number of ways to do this. I'm a believer that the classes that map to database tables should be left 'pure', and only contain properties that reflect the actual fields in the database, but either way the process is similar.

You can create a model class that holds the required information to display in the View:

public ViewResult Details(int id)
{
    UserInformation info = ... // get the information object from the database

    UserInformationModel model = new UserInformationModel {
        Id = info.Id,
        Details = String.Join(" ", new[] { info.Name, info.Address, info.PhoneNumber }) );
    }

    return View(model);
}

Alternative if you want to add it to your databound object:

public class UserInformation
{
    ...
    public string Details
    {
        get
        {
             return String.Join(" ", new[] { info.Name, info.Address, info.PhoneNumber });
        }
    } 
    ....
}

And then pass the entire data object to the view instead of a specific model.

Michael Shimmins