开发者

asp.net mvc database model dynamic Properties

开发者 https://www.devze.com 2023-01-16 02:17 出处:网络
Im just wondering how you go about creating dynamic properties on entities that generated from a database generated model.

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 开发者_StackOverflowname, 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消