I'm using EF4.x Self Tracking Entities in my project and am trying to achieve Model Validation in my MVC4 web application, however, my Model State always seems to be Valid. I'm using T4 templates to generate my "buddy" classes. Below is an example of one of the STE's and its buddy:
STE - generated using T4:
[DataContract(IsReference = true)]
[KnownType(typeof(Filing))]
public partial class FilingHistory: IObjectWithChangeTracker, INotifyPropertyChanged
{
public int FilingHistoryId
{
//Snipped for Brevity
}
// Navigation, ChangeTracking, Association Fix up snipped
}
Here is the Buddy Class generated also via a T4 template I wrote:
[MetadataType(typeof(FilingHistoryMetaData))]
public partial class FilingHistory
{
// Partial Class
}
public class FilingHistoryMetaData
{
[Display(Name = "Filing History Id")]
[Required(ErrorMessage = "Filing History Id is Required.")]
int FilingHistoryId { get; set; }
// Other properties snipped for Brevity
}
I'm going to exclude the key's from each MetaData class because those will be created automatically (just as an fyi). Also, the namespaces for the STE, the empty partial and the buddy class are identical
When I create a simple controller in MVC4 just to test it out, with a Create Template, on the HttpPost Action of Create I have some code as shown below:
[HttpPost]
public ActionResult Create(FilingHistory filingHistoryToCreate)
{
if (ModelState.IsValid) // THIS IS ALWAYS TRUE! even if i pass nothing<----
{
return Redirect("/");
}
return View(filingHistoryToCreate);
}
I read through a bunch of SO links and even went through MSDN, and I think I have everything setup correctly, i.e. namespaces are fine so there is no naked partial class stuff going on.
When my view renders I leave all the textboxes empty, I set a breakpoint to inspect by entity and nothing has been set, yet the model is valid. I also tested by entering some garbage into the textboxes to ensure the model binding was working fine, and it was...
I tried also testing using a console application, and I found out that you have to take an additional step of registering the MetaData type, but I beleive in MVC this isnt required. In case it helps anyone - the console app and registering meta data type didn't work for me either, so I'm thinking my buddy class may be the culprit?
It seems the DataAnnotationsModelMetadataProvider is looking for the public properties when checks for the attributes.
Change your FilingHistoryId to public and it should work:
public class FilingHistoryMetaData
{
[Display(Name = "Filing History Id")]
[Required(ErrorMessage = "Filing History Id is Required.")]
public int FilingHistoryId { get; set; }
// Other properties snipped for Brevity
}
Related
My understanding is that only one model can be passed to the view at a time. The problem with this that I see is that I am being forced to pass the Entity Framework model, and not any model that will manage housekeeping in the view. Here is what I mean:
You need to make a page that allows someone to submit Cars to the database. Along with the form fields (e.g. CarName, CarMake, CarYear) you also need a checkbox at the bottom of the page called "Remember Values" which when checked will "remember" the form values when the user clicks the Submit button at the bottom, so when they return all of their form data is still in the form fields. Needless to say, this Remember Values variable is not part of the Entity Framework model- it is just a housekeeping variable for use in the view.
How would you guys handle adding this checkbox? It feels like it should be part of the model, but I can't send two models to the view. Am I just looking at this issue wrong? What would you recommend?
.NET 4.5/MVC 5/EntityFramework 6
This is a good situation to be using ViewModels.
Build your ViewModels with all properties that you'd want to send/retrieve to/from your view. For example:
EF Entity
public class Car {
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual string Make { get; set; }
public virtual string Year { get; set; }
}
View Model
public class AddCarViewModel {
public Car Car { get; set; }
public bool RememberValues { get; set; }
}
Controller
public class CarController : Controller {
// Constructor....
public ActionResult Add() {
var vm = new AddCarViewModel();
return View(vm);
}
[HttpPost]
public ActionResult Add(AddCarViewModel vm) {
if (ModelState.IsValid) {
_carService.Save(vm.Car);
}
return View(vm);
}
}
Another good approach is to create Domain Transfer Objects, which are POCO classes to hold data that is transferred through the pipes. For example, in your business layer you may want to audit any changes to your Car model. So you may have properties like CreatedBy, CreatedDate, UpdatedBy, UpdatedDate, etc. (These properties are generally never displayed to the end-user but are important to store).
So you'd create the following classes:
public class Car {
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual string Make { get; set; }
public virtual string Year { get; set; }
public virtual User CreatedBy { get; set; }
public virtual User UpdatedBy { get; set; }
public virtual DateTime CreatedDate { get; set; }
public virtual DateTime UpdatedDate { get; set; }
}
public class CarDTO {
public Guid Id { get; set; }
public string Name { get; set; }
public string Make { get; set; }
public string Year { get; set; }
}
and you can use a library such as AutoMapper to map properties from Car -> CarDTO:
var car = _carService.GetCarById(id);
var carDTO = Mapper.Map<Car, CarDTO>(car);
This way, you can choose which properties you want exposed to your views by utilizing DTO's.
I always create an additional model that I can convert to and from between the EF model.
This additional model gets passed to the View and holds al the neccesary properties like CarName, Carmake, CarYear, Remember and probably most importantly, the Id of that particular object.
So when the user submits, this model gets passed to the Post method where you can extract all the required properties. You fetch the database model using the Id from your DbContext and update the properties with the values that were just passed through.
Technically you can send two models to the view, if the model is actually something like a Tuple:
#model Tuple<SomeEFModel, SomeViewModel>
Though that's kind of ugly. And if you're creating a view model anyway you might as well just make it a composite of the Entity Framework model. Something like:
public class SomeViewModel
{
public SomeEFModel EFModel { get; set; }
public string SomeOtherProperty { get; set; }
// other stuff...
}
Then just build an instance of that in the controller and send it to the model:
#model SomeViewModel
You could even just de-couple the EF model and the view model entirely, creating a custom view model that has everything for that view and then translating to/from that and the EF model at the controller level. Ultimately it comes down to what implementation looks cleaner and is easier to maintain, which can differ from one context to another.
Edit: Another option, if the models get unwieldy for whatever bits of the framework you're relying on, could be to separate your outgoing and incoming models. For pushing data to the view, you can use the composite view model above. But then when the data comes back from the view just use a normal Entity Framework model and a couple of additional parameters for your additional fields:
public ActionResult Edit(int id)
{
// build the view model with the EF model as a property
return View(someViewModel);
}
[HttpPost]
public ActionResult Edit(SomeEFModel model, string someOtherProperty)
{
// here you have an EF model from the view like normal
// plus the additional property (however many you need)
// you can even create a separate view model to collect the other properties
// as long as the names are well defined, the model binder should build both
}
First, you absolutely should NOT be passing your EF models directly to your view, and you should certainly NOT be posting directly to your EF models. This is essentially taking untrusted, unsanitized input and directly writing it to your data model with only bare minimal validation.
While this may work with simple models with no security or other ramifications, imagine a situation where you allowed a user to edit his profile information. Further, imagine that in his profile you also stored information relating to his subscription information. A specially crafted submit could alter his subscription information and give himself free access to your site, or worse...
Instead, you use view models. Apart from the security aspects, view models are good because other than in very simple CRUD style sites, your views requirements are typically different from your data models requirements. For instance, a particular field might be nullable in your data model, but you might want to make it required in your view. If you pass your model directly, then you can't do that easily.
Finally, Aggregate view models aggregate many different submodels to provide an overall model for the view, which is what you are getting at. You would then use a service layer, repository, or business logic layer to translate your view model to your data model, massaging data or applying logic as needed.
So I am new to MVC and am working now with MVC3 and the Entity Framework. I am currently using a Model/Schema 1st approach as the database already exists. Therefore I create my ADO.NET Entity Data Model (.edmx) and I have all the needed entities in my MVC app. So far so good on all this.
However let's say one of my Entities is a 'Customer' entity. I can see the auto-generated partial class inheriting from EntityObject in MyEntites.Designer.cs. At this point I want to add some custom business logic to my MVC Model. Natuarally I believe the answer is to use my own partial class created in the Model named 'Customer' as well.
I did a lot of searching on this before asking the question and see all kinds of information on POCO, T4 templates, modifying auto-generated code, etc and am lost. Is it a royal pain to add my own business logic and custom code to the auto-generated entities from EF? I certainly don't want to modify the auto generated code over and over.
I need a straight forward explanation to make the proverbial 'light bulb' go on, and then I can take-off from there. Can someone help me answer how to do this please?
Thanks!
Keep your own class code in a different file, but use the same class and namespace. This will help avoid your code being overwritten by the T4 code generator.
Extending Entity Framework Generated Types
You can also add attributes to generated classes by using a meta class:
Adding Attributes to Generated Classes
Those codes are auto-generated and will be over written on each model update or change.
You can achieve what you need through extending models. Suppose that EF generated the following entity class for you:
namespace YourSolution
{
using System;
using System.Collections.Generic;
public partial class News
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
public virtual UserProfile User{ get; set; }
}
}
and you want do some work arounds to preserve your you data annotations and attributes. So, follow these steps:
First, add two classes some where (wherever you want, but it's better to be in Models) like the following:
namespace YourSolution
{
[MetadataType(typeof(NewsAttribs))]
public partial class News
{
// leave it empty.
}
public class NewsAttribs
{
// Your attribs will come here.
}
}
then add what properties and attributes you want to the second class - NewsAttribs here. :
public class NewsAttrib
{
[Display(Name = "News title")]
[Required(ErrorMessage = "Please enter the news title.")]
public string Title { get; set; }
// and other properties you want...
}
Notes:
1) The namespace of the generated entity class and your classes must be the same - here YourSolution.
2) your first class must be partial and its name must be the same as EF generated class.
Go through this and your attribs never been lost again ...
Ok I've just ran into this and I was only supposed to be checking my emails however I've ended up watching this (and not far off subscribing to TekPub).
http://tekpub.com/production/starter
Now this app is a great starting point, but it raises one issue for me and the development process I've been shown to follow (rightly or wrongly). There is no conversion from the LinqToSql object when passing data to the view. Are there any negitives to this?
The main one I can see is with validation, does this cause issues when using MVC's built in validation as this is somthing we use extensivly. Because we are using the built in objects generated by LinqToSql how would one go about adding validation, like
[Required(ErrorMessage="Name is Required")]
public string Name {get;set;}
Interested to understand the benifits of this methodology and any negitives that, should we take it on, experiance through the development process.
Should this be taken as a guide and we should be using ViewModels? If so should we always use them even in simple cases? And how/where in the application logic does the Entity get converted to a ViewModel?
With entity objects, you could use buddy classes, whereby you create a second class which acts as a metadata provider for your entity. For instance, with a Customer entity generated by Linq-to-Sql, I could create a buddy class like so:
[MetadataType(typeof(CustomerMeta))]
partial class Customer {
}
public class CustomerMeta {
[DisplayName("Forename", Required(ErrorMessage = "Forename is required.")]
public string Forename { get; set;}
}
Entities are generated as partial classes so you can add your own code to them.
Alternatively, you could forego pushing your entity types to your views and create specific models based around the functionality required, for instance I would typically have a User entity, but when I need to create a User, I have something called a CreateUserSpec model:
public class CreateUserSpec
{
[DisplayName("Forename")]
public string Forename { get; set; }
}
Which has a subset of the properties of the User, only those required to create a User. This is the model I would pass to my view, and repopulate from the form data. For instance:
public class AccountController
{
public ActionResult Register() {
return View(new CreateUserSpec());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(CreateUserSpec spec) {
if (!ModelState.IsValid) {
return View(spec);
}
var user = UserFactory.CreateUser(spec);
// Redirect to authorisation page?
}
}
I'm actually fine with using another validation method. It seems there aren't many options prebuilt for doing validation with ASP.NET MVC 1.0. The main thing I see people talking about is xVal. However, there is literally no documentation for it. In fact, the blog of the founder seems to only have like two posts on it.
Anyway, it's the only thing I've seen that can also provide client validation. My issue is that I cannot use attribute based stuff because I'm generating my models using LLBLGen and I don't want to modify the code.
Everything I've read about xVal talks about the possibility of implementing an IRulesProvider but no real info of how to go about doing that and using it. I've found some code that implements it but using attributes which I can't really do.
So can anyone provide some guidance on how to use xVal if I'm not hand coding my model classes or going to use DataAnnotations or something similar (I'm open to an alternative to xVal but I haven't seen anything and I need to stick with ASP.NET MVC 1.0 and I need client side validation support)?
Edit: I don't think a partial class approach will work for me because I will be generating the code a lot and they will be in different assemblies.
You can use xVal with LLBLGen or any other ORM generated classes by using the MetadataType attribute on a partial class. For example if you have a LLBL generated entity called UserEntity you would create a partial class and mark it up with a MetadataType attribute like this:
[MetadataType(typeof(UserEntityMetaData))]
public partial class UserEntity
{
}
You will than create the Meta class where you can markup the properties with the appropriate attributes like this:
public class UserEntityMetaData
{
[Required()]
[StringLength(50)]
[DataType(DataType.EmailAddress)]
public object EmailAddress { get; set; }
[Required()]
[StringLength(32)]
[DataType(DataType.Password)]
public object Password { get; set; }
[Required()]
[StringLength(25)]
public object FirstName { get; set; }
[Required()]
[StringLength(25)]
public object LastName { get; set; }
}
This will allow you to not have to change the LLBL generated code, just your custom partial classes. The only catch is that you will want both the partial class and the Meta class in the same namespace as the generated entity classes. You do not have to do this, but it makes things easier when you call the xVal validation.
In addition to what jcerhea said you also need to modify how the DataAnnotationsValidationRunner class is set up to handle the "buddy" classes in the GetErrors method, e.g.
namespace Entities
{
public static class DataAnnotationsValidationRunner
{
public static IEnumerable<ErrorInfo> GetErrors(object instance)
{
var metadataAttrib = instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();
var buddyClassOrModelClass = metadataAttrib != null ? metadataAttrib.MetadataClassType : instance.GetType();
var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass).Cast<PropertyDescriptor>();
var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType()).Cast<PropertyDescriptor>();
return from buddyProp in buddyClassProperties
join modelProp in modelClassProperties on buddyProp.Name equals modelProp.Name
from attribute in buddyProp.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(modelProp.GetValue(instance))
select new ErrorInfo(buddyProp.Name, attribute.FormatErrorMessage(string.Empty), instance);
}
}
}
I have a standard Domain Layer entity:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set;}
}
which has some kind of validation attributes applied:
public class Product
{
public int Id { get; set; }
[NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
public string Name { get; set; }
[NotLessThan0]
public decimal Price { get; set;}
}
As you can see, I have made up these attributes completely. Which validation framework (NHibernate Validator, DataAnnotations, ValidationApplicationBlock, Castle Validator, etc) in use here is not important.
In my client layer, I also have a standard setup where I don't use the Domain entities themselves, but instead map them to ViewModels (aka DTO) which my view layer uses:
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set;}
}
Let's then say that I want my client/view to be able to perform some basic property-level validations.
The only way I see I can do this is to repeat the validation definitions in the ViewModel object:
public class ProductViewModel
{
public int Id { get; set; }
// validation attributes copied from Domain entity
[NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
public string Name { get; set; }
// validation attributes copied from Domain entity
[NotLessThan0]
public decimal Price { get; set;}
}
This is clearly not satisfactory, as I have now repeated business logic (property-level validation) in the ViewModel (DTO) layer.
So what can be done?
Assuming that I use an automation tool like AutoMapper to map my Domain entities to my ViewModel DTOs, wouldn't it also be cool to somehow transfer the validation logic for the mapped properties to the ViewModel as well?
The questions are:
1) Is this a good idea?
2) If so, can it be done? If not, what are the alternatives, if any?
Thank you in advance for any input!
If you're using something supporting DataAnnotations, you should be able to use a metadata class to contain your validation attributes:
public class ProductMetadata
{
[NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
public string Name { get; set; }
[NotLessThan0]
public decimal Price { get; set;}
}
and add it in the MetadataTypeAttribute on both the domain entity & DTO:
[MetadataType(typeof(ProductMetadata))]
public class Product
and
[MetadataType(typeof(ProductMetadata))]
public class ProductViewModel
This won't work out of the box with all validators - you may need to extend your validation framework of choice to implement a similar approach.
The purpose of validation is to ensure that data coming into your application meets certain criteria, with that in mind, the only place it makes sense to validate property constraints, like those you have identified here, is at the point where you accept data from an untrusted source ( i.e. the user ).
You can use something like the "money pattern" to elevate validation into your domain type system and use these domain types in the view model where it makes sense. If you have more complex validation (i.e. you are expressing business rules that require greater knowledge than that expressed in a single property), these belong in methods on the domain model that apply the changes.
In short, put data validation attributes on your view models and leave them off your domain models.
Why not use an interface to express your intent? Eg:
public interface IProductValidationAttributes {
[NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
string Name { get; set; }
[NotLessThan0]
decimal Price { get; set;}
}
It turns out that AutoMapper may be able to do this for us automagically, which is the best case scenario.
AutoMapper-users: Transfer validation attributes to the viewmodel?
http://groups.google.com/group/automapper-users/browse_thread/thread/efa1d551e498311c/db4e7f6c93a77302?lnk=gst&q=validation#db4e7f6c93a77302
I haven't got around to trying out the proposed solutions there, but intend to shortly.
If you use hand-written domain entities, why not put your domain entities in their own assembly and use that same assembly both on the client and server. You can reuse the same validations.
I've been considering this as well for a while now. I totally understand Brad's reply. However, let's assume I want to use another validation framework that is suitable for annotating both domain entities and view models.
The only solution I can come up with on paper that still works with attributes would be to create another attribute that "points" to a domain entity's property that you are mirroring in your view model. Here's an example:
// In UI as a view model.
public class UserRegistration {
[ValidationDependency<Person>(x => x.FirstName)]
public string FirstName { get; set; }
[ValidationDependency<Person>(x => x.LastName)]
public string LastName { get; set; }
[ValidationDependency<Membership>(x => x.Username)]
public string Username { get; set; }
[ValidationDependency<Membership>(x => x.Password)]
public string Password { get; set; }
}
A framework like xVal could possibly be extended to handle this new attribute and run the validation attributes on the dependency class' property, but with your view model's property value. I just haven't had time to flesh this out more.
Any thoughts?
First of all, there is no notion of "standard" domain entity. For me, standard domain entity does not have any setters to begin with. If you take that approach, you can have more meaningful api, that actually conveys something about your domain. So, you can have application service that processes your DTO, creates commands that you can execute directly against you domain objects, like SetContactInfo, ChangePrice etc. Each one of these can raise ValidationException, which in turn you can collect in your service and present to the user. You can still leave your attributes on the properties of dto for simple attribute/property level validation. For anything else, consult your domain. And even if this is CRUD application, i would avoid exposing my domain entities to presentation layer.
Disclaimer: I know this is an old discussion, but it was closest to what I was looking for: Keeping DRY by reusing validation attributes. I hope it is not too far from the original question.
In my situation I wanted to make error messages availible in .NET views and in other viewmodels. Our entities have little to no business logic and are mainly targeted for data storage. Instead we have a large viewmodel with validation and business logic were I want to reuse error messages. Since the users are only conserned with error messages, I find this to be relevant as that is what is important to maintain easily.
I could not find a feasible way to remove logic from the partial ViewModels, but I found a way to convey the same ErrorMessage, such that it can be maintained from a single point. Since ErrorMessages are tied to the view, it can just as well be part of the ViewModel. Consts are considered static members, so defining the error messages as public string constants, we can access them outside the class.
public class LargeViewModel
{
public const string TopicIdsErrorMessage = "My error message";
[Required(ErrorMessage = TopicIdsErrorMessage)]
[MinimumCount(1, ErrorMessage = TopicIdsErrorMessage)]
[WithValidIndex(ErrorMessage = TopicIdsErrorMessage)]
public List<int> TopicIds { get; set; }
}
public class PartialViewModel
{
[Required(ErrorMessage = LargeViewModel.TopicIdsErrorMessage]
public List<int> TopicIds { get; set; }
}
In our project we were using custom html for dropdownlists, such that we could not use #Html.EditorFor helper in razor, thus we could not use unobtrusive validation. With the error message availible we could now apply the necessary attributes:
#(Html.Kendo().DropDownList()
.Name("TopicIds")
.HtmlAttributes(new {
#class = "form-control",
data_val = "true",
data_val_required = SupervisionViewModel.TopicIdsErrorMessage
})
)
Warning: You might need to recompile all related projects that rely on const values...