Entity Framework - additional dynamically calculated properties for business objects / models (ASP.NET MVC)

Let's say that I have a Customer model with the following fields: Id, FirstName, LastName. I want to present a list of customers in a list view. To do this, I use my service method, which returns a List to iterate through the view.

But now I also want to display some additional information for each client, for example, a loan. This information is not stored in a specific field in the database, but should be calculated based on Transacitons data. Where should I do this calculation?

I can have an extra field called “Credit for customer model” and do it in getter, but I'm not sure if this is the best way, especially that inside od Model I do not have access to the EF context.

+3
source share
1 answer

Assuming your question is correctly phrased, and this is really for display, and not for business processes (which would be a completely different question) ...

Do it in your presentation model. Add the inputs you need, project onto them and calculate the result. Here is a very trivial example. The real world is more complicated.

class Person // entity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class PersonPresentation
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DisplayName 
    {  
        get 
        { 
            return string.Format("{0} {1}", this.FirstName, this.LastName);
        }
    }
}

public ActionResult DisplayPeople()
{
    var model = from p in Repository.AllPeople()
                select new PersonPresentation
                {
                    FirstName = p.FirstName,
                    LastName = p.LastName
                };
    return View(model);
}
+5
source

Source: https://habr.com/ru/post/1736350/


All Articles