Simple data manipulation: in Entity Model or Business layer? - c#

I'm working on an asp.net MVC application that implements the traditional Data/ Business/Presentation layered approach.
One of my entity models (representing a person) contains address/contact information including a field for "State". My data source (which I have little control over) provides state values in full-text (Ex: "California" vs "CA", "Florida" vs "FL", etc).
I created a static helper class that we intend to use to transform the full-text values to their abbreviations.
My question is, where should this helper class be referenced and where should the transformation take place?
I see the following options:
Use an accessor in the model that references this static class and performs the transformation on get. Something along the lines of:
public string State
{
get
{
return StateConverter.Abbreviate(_state);
}
}
perform the conversion in the business layer whenever this entity model used
Perform the conversion in the presentation layer whenever this value is displayed
I like the simplicity of having this take place in the actual model (via get accessor), but this smells a tiny bit like business logic. The other options mean that I will have to convert this in many places (duplicating logic, traversing through people lists, etc).
Thanks.

It is okay to put it inside your model since it is just a computed field. Moreover your Abbreviate(...) method doesn't even depend on any data outside your model. Your right to put it there.

Related

Two ViewModels for one View

I am developing a Web-App using ASP.NET MVC and I've been trying to avoid using the ViewBag, therefore I created few viewmodels to populate my drop-downs and in general to pass the data I need in my views. At the same time I would like to keep the data binding clean and avoid properties that will not be bound to (without using include/exclude attributes) and I've been told that obviously returnmodels are great for that purpose.
So is creating two independent models for one view a bad idea? One with all the data that needs to be displayed and another one only with the fields from my form or is this an excess of form over substance and should I reconsider changing my design?
Edit: A quick example because I'm not too good at explaining
class ViewModelA{ // passed to the view and then bound to when form is submitted
List<KeyValuePair<int, string>> DropDownValues; // will be always empty while databinding
int SelectedValue; // will be always 0 when passed to the view
...
}
Should I replace ViewModelA with
class ViewModelB{ // contains data passed to the view
List<KeyValuePair<int, string>> DropDownValues;
...
}
class ReturnModel{ // contains data returned from the view
int SelectedValue;
...
}
Obviously here I could just bind directly to my model but let's assume it's more complex and the data has to be processed before saved.
I think I know what you are asking. You are saying you have a viewmodel with, lets say, these properties: Age, Name, CountryOfResidence (for dropdown), and a few more properties. But when you create a new person, you only post Age, Name, IdOfCountry to controller.
So your question is what is the point of posting the whole viewmodel, when it is not needed. Fair question.
There are many ways you can do this. Here is one way:
Create a base class with common properties (for posting)
Create a derived class with more properties for the view.
Some people will refer to 1 as Data Transfer Object (DTO). These DTO's will be shared for communication between presentation layer, service layer, business layer, data access layer etc.

Should I use same Enums definitions in ViewModel(UI layer) and domain Model(Business layer)?

I have read about separating domain models and models used to render views. As far as I understand it for every domain model I can(recommended to) create a model in my MVC/UI layer and while bringing data from business layer I populate my UI model. int, float is all fine I just populate them.
How should I handle enums?
should I create a different enum definition all together in my UI layer and then map the enum also while bringing information from my business layer to UI layer? or is it fine having the same enum defined in my business layer to be used in my UI layer as well?
Use the same enums. That will reduce confusion, give you just one place to look things up, and make it easier if you ever need to make changes.
The model/view separation is useful for keeping logic unentangled, but using a single set of enums will not impede that.
One exception I would make would be if you needed to keep different parts of your code from sharing headers because you expected to do a lot of conditional compilation or linking, but it doesn't sound like the case here.
Well, actually enums are int (most of the time) shortcuts.
If you want to use auto dropdownlist's for enums and change the texts, or if you want to "close" your DAL as a project, by example, it may be usefull to make something like
public enum ADalEnum : int
{
One = 1,
Two = 2,
Three = 3
}
...
public enum MappedEnum : int
{
One_Little_Indians = ADalEnum.One,
Two_Little_Indians = ADalEnum.Two,
Three_Little_Indians = ADalEnum.Three,
}
So it will be "the same".

C# Modelbinding custom object

I have a class that convert between physical units, based on an enum collection. In code you can switch the engineerin unit on the enum, and the object will calculate the engineering value based on the internal (SI) unit.
Now I have created an editortemplate for MVC to input a value and its engineering unit.
My problem now resides in that the ModelBinder assigns the properties in the wrong way around, the unit should be assigned before the value otherwise the internal value is calculated wrong. The internal value is calculated as soon as the engineering value is assigned.
I can create a custom model binder to assign the properties in the right order, however sometimes the same editortemplate is used several times on the same viewpage, how would I deal with that in the customer model binder?
-Edit-
I can also make viewmodels for each of the "smart" objects, and translate them in the controller, but not sure this is appropiate, this would mean I have to create dummy objects for each physical unit, but obviously would seperate my view properly from my framework/logic
Best Regards,
Martin
This is something of a design question.
I would recommend using a separate view model that doesn't depend upon assigning values in a specific order, and then mapping the values to the class you have at the controller. Pre-controller logic (action filters and model binders) step out of the controller based work flow, which is a decision that shouldn't be made lightly.

Where Do You Store Data in a GUI Application?

I've always heard that you should separate GUI/Data/Logic components, like the MVC pattern.
So, I am wondering: In a GUI application, where do you actually store the data?
Here is an example (using C# terminology):
Suppose you have a GUI that takes user input, does some analysis, and displays results in a table. The user can have several analyses in one window, so there is a ListView at the bottom that allows the user to select which analysis is currently displayed (the selected item gets displayed).
In order to display this, the analysis data must be stored somewhere. I have always done one of two things:
Put all the data into a single object and store it in the ListViewItem's "Tag" property
Extend "ListViewItem" and just add whatever properties I need.
But, this means I am storing the data inside of the ListViewItem.
Is there a more appropriate place to keep track of the data?
I could add it as private members to the main form, but that seems like the same thing.
The only other thing I can think of is to make some global class that I can reference whenver I need to.
Thanks.
As I understand, you have some ListViewItems. Each ListViewItem is associated with your business logic object and after select one of ListViewItem you want make some operations over this buisness object. In similar situations I usually make Data Object like
struct MyDataObject
{
string Id;//very often data object need to have Identifcator, but not always
//some fields
}
and add to data object constructors for typical user input.
After that I make business logic layer contains available algorithms for this data objects. For simple projects, this is a static class like
static class MyDataObjectOperationService{
void MakeSomething(MyDataObject myDataObject);
object GetSomething(MyDataObject myDataObject);
...
}
For big projects that is usually interface. Also I usually make a data layer interface for getting this data object. For example
interface IMyDataObjectRepository{
IList<MyDataObject> GetAll();
MyDataObject GetById(string id);
//CRUD operations if it need
}
After that I put into ListViewItems ids of Data Objects and on ListViewItemClick getting selecting id, after that getting DataObject by Id using data layer classes and make some operations using business logic layer classes. If I need to save DataObject changes or create new DataObject I using data layer classes.

ASP.Net Mvc - Is it acceptable for the View to call functions which may cause data retrieval?

I am currently playing around with the Asp.Net mvc framework and loving it compared to the classic asp.net way. One thing I am mooting is whether or not it is acceptable for a View to cause (indirectly) access to the database?
For example, I am using the controller to populate a custom data class with all the information I think the View needs to go about doing its job, however as I am passing objects to the view it also can cause database reads.
A quick pseudo example.
public interface IProduct
{
/* Some Members */
/* Some Methods */
decimal GetDiscount();
}
public class Product : IProduct
{
public decimal GetDiscount(){ ... /* causes database access */ }
}
If the View has access to the Product class (it gets passed an IProduct object), it can call GetDiscount() and cause database access.
I am thinking of ways to prevent this. Currently I am only coming up with multiple interface inheritance for the Product class. Instead of implementing just IProduct it would now implement IProduct and IProductView. IProductView would list the members of the class, IProduct would contain the method calls which could cause database access.
The 'View' will only know about the IProductView interface onto the class and be unable to call methods which cause data access.
I have other vague thoughts about 'locking' an object before it is passed to the view, but I can foresee huge scope for side effects with such a method.
So, My questions:
Are there any best practices regarding this issue?
How do other people using MVC stop the View being naughty and doing more to objects than they should?
Your view isn't really causing data access. The view is simply calling the GetDiscount() method in a model interface. It's the model which is causing data access. Indeed, you could create another implementation of IProduct which wouldn't cause data access, yet there would be no change to the view.
Model objects that do lazy loading invariably cause data access when the view tries to extract data for display.
Whether it's OK is down to personal taste and preference.
However, unless you've got a good reason for lazy loading, I'd prefer to load the data into the model object and then pass that "ready-baked" for the view to display.
One thing I am mooting is whether or not it is acceptable for a View to cause (indirectly) access to the database?
I've often asked the same question. So many things we access on the Model in Stack Overflow Views can cause implicit database access. It's almost unavoidable. Would love to hear others' thoughts on this.
If you keep your domain objects "persistent ignorant", then you don't have this problem. That is, instead of having getDiscount inside your Product class, why not just have a simple property called Discount? This would then be set by your ORM when loading the instance of the Product class from the database.
The model should not have methods ("actions") that consist of data access. That's the DAL's concern. YOu could have a discount percent property stored in the product class and have the GetDiscount method return a simple calculation such as Price * (100 - discountPercent) or something like this.
I disconnect my business entities (Product in your example) from data access. That's the repository (in my case) 's concern.
I've built a site in MonoRail before that sometimes has methods that trigger data access from the view. I try to avoid it because when it fails, it can fail in unusual and unfixable ways (I can't really try/catch in an NVelocity template, for example). It's totally not the end of the world--I wrote well-abstracted PHP sites for years that accessed the database from the view and they still work well enough because most of the time if something blows up, you're just redirecting to a "Something didn't work"-type error page anyway.
But yeah, I try to avoid it. In a larger sense, my domain model usually doesn't trickle all the way down into the view. Instead, the view is rendering Document objects that are unashamedly just strongly-typed data dumps, with everything pre-formatted, whipped, crushed, and puree'd to the point where the view just has to spit out some strings with some loops and if/else's, transform the number "4" into 4 star images, etc. This document is usually returned by a Web service that sits in front of the beautiful domain model, or it's just a simple struct that is constructed in the controller and passed along as part of the ViewData. If a domain object is used directly, then it usually doesn't do anything to explicitly trigger data access; that's handled by a collection-like repository that the view doesn't have access to and the domain objects usually don't have access to, either.
But you don't have to do it that way. You could just be discplined enough to just not call those methods that touch the database from the view.

Categories