How to get model data annotations to implement application validation without implementing at DB level as well using EF? - asp.net-mvc-3

I like the idea of using the data annotations to specify validation of fields within the Model. However in EF I notice that it wants to implement this at DB level ie [Required] becomes a "not null" field. Is it possible to just have the application apply this validation without changing the database?
Thanks,
Ed

What you can do is to use a separate view model for the views and separate entity classes for the database. And you can map those objects using a library like auto mapper.

Related

MVC sharing Servicestack Model (ormlite)

I'm new to MVC. I come from Webforms, by the way I was also using Servicestack ormlite.
I need to know if I can have an MVC project, but the Model section can be in a different assembly, so I can share this assembly with other projects (console app, web api, mvc project).
It is important that the assembly can have the Model section using the servicestack functionality for model(s) definition(I use servicestack ormlite for data layer), so here comes my other question, that servicestack's model(s) definition can it be used for the "views" in the MVC project? ie, the models syntaxis for servicestack is compatible with the strong typed models in the views MVC?
do you have a sample of:
models in external assembly
share models definition for DAL in servicestack(ormlite), and working in the views for the MVC project
Thanks in advance.
OrmLite is very flexible and resilient in what clean POCOs you can use with it, from a previous answer:
Clean POCOs
The complex Data Models stored in OrmLite or Redis doesn't suffer from any of these issues which are able to use clean, disconnected POCOs. They're loosely-coupled, where only the "Shape" of the POCO is significant, i.e. moving projects and changing namespaces won't impact serialization, how it's stored in RDBMS tables, Redis data structures, Caching providers, etc. You're also not coupled to specific types, you can use a different type to insert data in OrmLite than what you use to read from it, nor does it need to be the "exact Shape", as OrmLite can populate a DTO with only a subset of the fields available in the underlying table. There's also no distinction between Table, View or Stored procedure, OrmLite will happily map any result-set into any matching fields on the specified POCO, ignoring others.
Effectively this means POCOs in ServiceStack are extremely resilient and interoperable, so you can happily re-use the same DTOs in OrmLite and vice-versa without issue. If the DTO and Data models only deviate slightly, you can hide them from being serialized or stored in OrmLite with the attributes below:
public class Poco
{
[Ignore]
public int IgnoreInOrmLite { get; set; }
[IgnoreDataMember]
public int IgnoreInSerialization { get; set; }
}
Otherwise when you need to separate them, e.g. more fields were added to the RDBMS table than you want to return, the DTO includes additional fields populated from alternative sources, or you just want your Services to project them differently. At that point (YAGNI) you can take a copy of the DTO and add it to your Services Implementation so they can grow separately, unimpeded by their different concerns. You can then effortlessly convert between them using
ServiceStack's built-in Auto Mapping, e.g:
var dto = dbPoco.ConvertTo<Poco>();
The built-in Auto Mapping is also very tolerant and can co-erce properties with different types, e.g. to/from strings, different collection types, etc.

is this a good idea to implement validation in entity framework POCO entities in dabtase first?

It`s seems that the best place to implement validation is as close as possible to the database, so when I use entity framework the nearest objects are the entities, in my case the POCO entities.
The reason for that is that if I want to reuse this POCO entities, the validation is implemented in the POCO objects and then there are less posibilities to insert worng data in the database.
this also avoid that someone try to insert incorrect data in the databse creating another application, or because he does not implement the validation. So it is more secure.
One way to do that is using partial classes that extends the POCO entities and that implements the IValidatableObject interface and return a list of validationresult.
But other way is the following. I have a common assembly that has the following:
One interface that declare the methods that need to implement the repositories.
The POCO entities that will be used by the repositories.
One class with utilities, such as copy entities and methods to validate the data of the entities.
Then I can create many repositories that use different versions of EF or another technology and all of them use the common assembly. This repositories implements the validation using the methods in the common library.
In this case I implement the validation only once. The only problem is that the repositories need to call the methods to validate the data.
But there are advantages in this way, from my point of view. For example, I can validate the data of the entities depending on the type of the operation. For example, if I am adding a new record and the primary key as an autonumeric, if the ID is not 0, then I can throw an exception, or if I try to delete a register when the ID is 0, then I don't need to send the command to the database.
So this second solution solves the problem to implement the validation as close as possible to the database, bacause is used in the repository, that is the element that access to the database, but has the problem that if some developer creates a new repository and not use the validation methods, I can have incorrect data in the database.
So my question is if the best option is to use validation with partial classes or to use a common library and the validation is implemented in the repositories, that is really what the users will use.
Thanks.
OK - phew, big question. My opinion is that the APPLICATION DOMAIN of the application is the boss of everything. The database is just an add-on service. So, the application domain should ultimately validate ALL objects that are being SENT somewhere. No need to validate object coming out of the DB because they were validated going in.
As an example, what if you were creating some object that needed to be sent off to a web service and it needed validation. Lets say it was never going near the database or the repositories. Once the DOMAIN business objects have been validated, they can then be sent for persistence or anywhere else.
Another thing to consider is what you mean by validation. Does it mean the datatypes are correct? Does it mean the business object is valid? Does it mean the business object is valid in the given context? It could mean all or only some of these things.
As an example, what if your system allows users to partially update records (common with very long input forms). The business object may only become valid when ALL the required data is captured, but the database allows persistence of "partial" data. In other words, you can save the business object to the database although it is not valid for further processing yet. etc etc....

ASP.NET MVC 3.0 - Maintain model state

Am new to ASP.NET MVC 3.0. Request expert's view on the below mentioned scenario.
I have a customer details page, where only Name is editable. There are 10 other customer properties that are non editable and displayed using SPAN. When user submits the page, I need to update only the Name.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
Anyone tried caching model (or viewmodel) using session id? Is it a good practice?
You are almost thinking in right direction.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
In Update Method **Load Customer again and update name Only as required and then save
**For 2 reasons
The first and most important rule is 'don't trust user data'. and
Concurrency and to avoid saving old data. See this example
Instead of using Session, I will suggest to use Hidden Field for record LastUpdateDateTime and Customer ID which will be posted back in the model to retrieve record and verify LastUpdatedtime with database record
Tipically, you should use a view model different than the database model. Having said that,in your current case the situation is very simple, submit only the name to the controller and then set the Name property of the object you get from EF with the submitted name.
Caching the view model or the model isn't your concern. The database model caching is handled by EF, your problem is mainly a lack of clear application layering. IN fact I strongly suggest to learn a bit more about the MVC pattern, basic application architecture (2-3 layering) and when and how to use a OR\M (which EF is).
use hidden inputs for other properties in your form. In that way you can get all properties binded to your EF entity and you dont need to get entity again from db.
#Html.DisplayFor(model=>model.x)
#Html.HiddenFor(model=>model.x)
or you can serialize the entity(if you use POCO entities) and set to hidden input. When you post back you should deserialize the entity.
My choice is always first one. :)

MVC3 (Models) ...what is the right way to display complex data on the view?

I’m having a philosophical problem with understanding how to use Models on MVC3.
I believe the problem lies from the fact that I come from WebForms :--)
Let's say I have 10 tables on my DB and as expected when I get them into my EF4, I get those Entity classes that represent the tables (and all their FK integer values).
When I want to display data on the View, I cannot display a select * from table because those FK integers means nothing to my users …and also because some data lies on related tables.
So my understanding is that I can create a Stored Proc, create a Complex Type that represent the actual data to display, coming from separate tables via different SQL joins.
QUESTION 1:
On the view, id MVC compliant to use as #model ..that Complex Type?
or shall I always use Models that are created on the Models folder? And if so, does that mean that I have to replicate the Complex Type on a new model inside the Models folder?
Question 2:
Is this the right way …to create specific SP to collect data that will be displayed or ..is it better to use linq and lambda to be applied to the EF4 Types that come from importing the DB into the EMDX designer.
Thoughts ??
FP
The correct way is to always define view models. View models are classes which are specifically tailored to the needs of a given view and would be defined in the MVC application tier. Those classes would contain only the properties that would be needed to be displayed by the view. Then you need to map between your domain models (EF autogenerated classes?) and the view models.
So a controller action would query a repository in order to fetch a domain model, map it to a view model and pass this view model to the view. Top facilitate this mapping you could use AutoMapper. A view shouldn't be tied to a domain model and always work with a view model. This works also the other way around: a controller action receives a view model from the view as action argument, maps it to a domain model and passes this domain model to the repository in order to perform some action with it (CRUD).
So a view model could be a class that is mapped from multiple domain models or multiple view models could be mapped to a single domain model. It all depends on how your domain looks like and how do you want to represent the information to the user.
As far as validation is concerned, I distinguish two types: UI validation and business validation. As an example of UI validation is: a field is required, or a field must be entered in a given format. A business validation is : the username is already taken or insufficient funds to perform wire transfer. UI validation should be done on the view models and business validation on the domain models.
I'm not sure why you need to use a stored proc, LINQ to Entities is able to generate complex types without needing to create stored procs (in most cases). You select subsets of data, just like you would with regular SQL.
As Darin says, the use of a View Model is appropriate for situations where you have a lot of complex data that isn't represented by a single entity. This View Model would contain multiple entities, or even multiple collections of entities. It all depends on how your data needs to be consumed.

Data Annotation on multiple table in asp.net MVC 2

I want to implement data annotation on three tables Link, LinkRef and LinkMeta. Link is main table and other two have LinkId as primary key. Because the system is multi-lingual Link title will be in more than one language so as other details. No of languages will vary. I want to know can i use data annotation in this scenario and if yes then how? Im using Linq2SQL for creating model.
Can Data annotations be applied to class objects?

Resources