Can Model communicate directly to the Data Access Layer? - c#

Sorry if im asking the question wrong but here is an example:
public class Person : BaseModel {
// somne properties like username, password, isLoggedIn
public Person(SomeDataService dataService){...}
public bool Login(){
var result = dataService.TryToLogin(this.username, this.password);
// do some stuff with result
}
}
Some people says it is acceptable but some them says not, so I don't know what is right.

You are legitimate to use any kind of code that works for you, MVVM is just a convention that should help you to code better and quicker, but if it doesn't work for you and there is no 3rd party (like your employer) that enforces this requests you are free to do whatever works the best for you.
Speaking of MVVM, this class above should be a Model, and if you want to respect the MVVM convention you can't do what you did, it should contain just plain properties. But as I said above someone must choose whether he wants to use MVVM at all, so if you haven't decided to stick to the MVVM convention you can use this code, just count on that it may be a bit confusing if you need someone else to work on that code too.

Related

Plain attribute or attribute with field?

I see a lot of code snippets with this example:
private string _possessor;
public string Possessor
{
get { return _possessor; }
set { _possessor = value; }
}
My questions is, why not just use plain property as in:
public string Possessor { get; set; }
I was reading on the internet, but could not really see the difference? You can either way set values in both examples and second example requires less coding and looks cleaner.
In the case that you are showing, it's true, there are no differences on doing each approach and the second one is cleaner. Knowing the first approach is useful because sometimes you need a property to do more than just get/set so in that case you will need to use the first approach.
You can also see here that with each new c# version, different ways of implement properties were created. The second approach is Auto-implemented properties
The main purpose of doing this is to help achieve data Encapsulation, which helps us by hidden the data in a class from other classes. this is also known as data-hiding.
Another good reason why this is done is when there some special validation or special business rules that needs to be checked before we set that particular value.
You can read more on Encapsulation from this site https://www.geeksforgeeks.org/c-sharp-encapsulation/

Asp.net C# model object binding

The product have some fields that can not be changed,
so I want to bind the object with only selected field.
For now I'm doing this(below) way (like binding manually), but I believe there is better and clean way. How to binding Model object to model object with only selected fields?
[HttpPut]
public JsonResult update(Product editedProduct) {
Product originalProduct = unitOfWork.ProductRepository.Get(filter: q => q.no == editedProduct.no).Single();
originalProduct.name = editedProduct.name;
originalProduct.modelNo = editedProduct.modelNo;
originalProduct.size = editedProduct.size;
originalProduct.color = editedProduct.color;
originalProduct.description = editedProduct.description;
originalProduct.price = editedProduct.price;
//originalProduct.upc = editedProduct.upc; //UPC can not be changed
//originalProduct.sku = editedProduct.sku; //SKU can not be changed
unitOfWork.Save();
return Json(new { success = true });
}
please advise me,
In my opinion there is absolutely nothing wrong with this approach. It is possible to do some things differently but it does not mean it is better.
Create a DTO/ViewModel class to represent the class you accept and return from the service. This way you can have different shapes of the data if you need it. For example you can skip a security critical field. I think this will be an improvement.
Use a framework like AutoMapper to do the mapping between the objects. This is quite popular approach but I personally prefer explicitly copying the fields.
You can update the object without retrieving it. I assume you are using Entity Framework. You can refer to this question for details - How to update a record without selecting that record again in ADO.NET Entity Framework? . I personally don't think that this will improve your code. I think you should do it only if you have performance issues with your current approach.
You can put the mapping code in your repository in an Update method or something.
BTW it seems like your repository is currently useless. You are just writing a wrapper around your ORM which makes the code more complex and more buggy. Repository is an anti-pattern when you are using an ORM. Your ORM is the repository.
Well, don't do it.
For this case you should create a separate ViewModel with only necessary fields.
I would not expose the setter in the class for example.
public class Product{
public string upc {get;}
}
This will not allow the property to be set.

Scaffolding or another framework?

Im a little confused. I saw some code in one of the projects where we use Linq To SQL
<MetadataType(GetType(Customer.CustomerMeta))> Partial Public Class Customer
Friend Class CustomerMeta
<Required(), StringLength(50)> Public Name As String
<Required(), StringLength(50)> Public Address As String
<Required(), StringLength(20)> Public EmailAddress As String
<StringLength(20)> Public Country As String
End Class
And wasnt sure why it was created like this but it looked like a different method had been used from what im used to.
After reading around it seemed like the technique maybe Scaffolding (http://msdn.microsoft.com/en-us/library/cc488469(v=vs.90).aspx) but half way through this walkthrough i realised that many areas dont exist (like the global.asax file) or apply to the project i saw the above code in therefore i could be on the wrong track here.
Does anyone know what technique/framework is being used above and if there are articles i could refer to, to get up to speed? If books or training course is required here then again im happy for someone to point me towards the right direction.
Thanks
These are data validation annotations (I don't know the exact 'framework' using them in your case, as they're exposed in the .NET framework and anyone programming against it can use them): basically, you can decorate members with these attributes (ValidationAttributes) and this metadata can then be used to do some validation, either manual or automated by some data schema rule checker.
In this case, the property Name is:-
a required field (i.e. it must have something in it, and not be empty),
and must be 50 characters in length
And so on and so forth.
The latter constraint might make the former redundant, depending on what's analysing the rules.

Exposing Data as C# Properties - Good or Bad?

I am kinda not getting my head around this and was wondering if someone could please help me understand this.
So here is the problem, I have a class in which there are no required parameters. If user does not set the fields I can take the default value and carry on. Previously, I designed the same class as Joshua Bloch's Builder Pattern (Effective Java) (immutable object). I didn't had any good reason for making the class immutable except for the fact that I didn't wanted to have telescopic constructors and I didn't wanted to expose the data of the class.
But now, a fellow programmer friend is trying to convince me that it's okay to expose the data from the class using C# properties. I am not sure about this and I still feel that I should not be allowing user to muck with data.
Maybe I am completely wrong in my understanding. Could someone please clear my doubt about this, that whether it's good or bad to expose the data from the class?
If it is good then in what case it is good? Or else if someone can please point me to the article/book that clarifies this I would really appreciate it.
Thanks!
Expose the data in the class if it is needed or of interest outside the class, and do not do so if it is not. Expose it read-only if it's only needed to be read outside, and expose it as a full read/write property if it should be able to be changed. Otherwise, keep it in a private field.
immutable classes are easier to reason about especially in a multi tasking application, but they usually pay in performance (because when you need to change the value of a field you need to build the whole class again with the new value).
So, you could be ok or (depending on what you're coding) even better off with properties but as usual there's no silver bullet.
Settable properties are also the only way to code objects for some specific frameworks or libraries (e.g. ORMs like NHibernate), because you can't control how the library/framework initializes the object.
About constructors, C# 4 has optional parameters, that could help you avoid a long chain of constructors and also communicate much more clearly the fact that the parameters are optional.
However I can't think of many cases where you would end up with classes with a long list of optional parameters. If you find that you're coding classes like that too often (especially with the builder pattern, which is very elegant looking on the consumers' side of the class but complicates the code for the class itself) you may be using the wrong design. Are you sure you are not asking your classes to have too many responsibilities?
It basically depend on what's the purpose of your Class in the application context (could you give us more details?).
Anyway reckon that you could make a property safe from external changes by declaring is setter as private:
http://msdn.microsoft.com/en-us/library/bb384054.aspx
public string UserName { get; private set; }
It's "good" when the consumer of the class needs the data. You have two possibilities to offer properties.
if you only want to offer a property for information purpose, then choose a read only property like this:
public string MyInformation { get; private set; }
If you have the need to allow the consumer to change that property, then make the setter public like that:
public string MyChangeableInformation { get; set; }
But if the consumer has no need to get the information, then hide it in your class!
But now, a fellow programmer friend is trying to convince me that it's
okay to expose the data from the class using C# properties. I am not
sure about this and I still feel that I should not be allowing user to
muck with data.
As a rule of thumb, methods should represent actions whereas properties represent data. What your friend might have tried telling you is that you can expose the data of your class to outside world and still maintain full control on how other classes are accessing the data. In your case, as other have mentioned, you can use properties with private setters, such that the caller should not be able to modify the data.

View Model Patterns and usage in ASP.NET MVC3 (Also, using EF 4.1)

I have been searching for an answer to this question for days and it is driving me insane. Currently I am working on a project using ASP.NET MVC 3 and am trying to utilize a ViewModel per controller approach as has been suggested by so many articles and tutorials I have checked out. To better illistrate what I am asking I will outline below:
Lets say I have a pretty simple and straight forward model. Users, Customers, Addresses, Phone Numbers, Orders, Products, Categories, etc... When a user registers for a new account on my site I would like to:
1) create an account for them (this is just an account id, customer type)
2) Add their customer demographic data to Customers
3) Add N-addresses and address types
4) Add N-phone numbers with type as well.
As far as I have got is deciding that I need a RegisterCustomerForRegistrationControllerViewModel. My predicament is what does this model look like? I am trying to be as DRY as possible yet when implementing this pattern I seem to repeat myself at each turn. At what level do I put DataAnnotations for validation? So do I simply new up a new Customer() even if I only want to use one property from the class in a given ViewModel?
I'm not even confident at this point that this is a correct assumption. There seems to be so much opinion on the topic yet so few concrete examples of implementation. I am hoping someone can point me in the right direction and maybe present some code snippets along the way... I hope this is all clear enough and if not please feel free to ask follow up questions.
Again, Thanks in advance!
Repeating simple properties across two distinct layers of an application is not a violation of DRY. Its just good design.
DataAnnotations go on ViewModels.
ViewModel will look something like
public class RegisterCustomerViewModel
{
[Required]
public string Name { get; set; }
public List<AddressViewModels> Addresses { get; set; }
public List<PhoneNumberViewModel> PhoneNumbers { get; set; |
}
Just like jfar, I would take a simple approache: one view, one view model with DataAnnotations.
That being said... I know how you feel (not confident) and I understand because I've been through that myself. My conclusions: unless you consider your web application to require the overhead of so many layers, principles and patterns, keep it simple. I believe that there is no perfect architecture. There's just what works and there's overhead. Sometime, what works is indeed complexe. Ask yourself if you need that complexity.
Take my first sentence as an answer to your question and the rest as my humble opinion.

Categories

Resources