MVC3 Validation with Entity Framework Model/Database First - asp.net-mvc

I want to use MVC 3 and the Entity Framework for my application.
The model will be stored in a different assembly to the MVC app.
The choice I'm making is either to use the EF to generate my entities or to use code first.
With code first, I can decorate members with [Required] etc... But how would I go about adding those attributes if EF has generated entities from the DB?
Having EF generate my entities will save a lot of time, but I want MVC to auto populate the validation depending on how I've decorated my members. Does this make sense? If so, how would I do that?

In that case, MetadataTypeAttribute is used. You can combine it with partial classes to achieve desired results
And by the way, in your place i would do more research when deciding between using Database First and Code First designs. That all is not about saving time when generating entities, there's much more difference between those two approaches. For the time saving purpose, you can use EF Power Tools to generate code first entities from database - simple.

Better than auto generating your entities, I recommend you to use Code First or mapping an existing database to POCO's classes (not generating the entities, just creating them by hand and mapping them to the existing database)
Scottgu wrote about using EF "Code First" with an existing database.

Check this out:
In your model template (file with extension model.tt) you can hack this template for generating decorators, in this example I add the [Required] decorator plus an error message
var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
foreach (var edmProperty in simpleProperties)
{
if(!edmProperty.Nullable)
{#>
[Required(ErrorMessage="<#=String.Format("The field {0} is required",edmProperty.ToString())#>")]<#
}#>
<#=codeStringGenerator.Property(edmProperty)#><#
}
}
So the result is something like this
[Required(ErrorMessage="The field Id is required")]
public long Id { get; set; }
PS: You can also add the
using System.ComponentModel.DataAnnotations; by editing the template.
Hope this can help you up.

Related

Error:'Unsupported context type' while creating a new controller

I am going to implement MvcMusicStore using ASP.NET MVC3, Linq to Sql class instead of Entity Framework, MS SQL Server 2008 pro instead of express ed.
I got the tutorial from mvcmusicstore.codeplex.com
I used Linq to Sql class and the Datacontext is MvcMusicSrotedataContext. When i try to create a new class using this
it shows an error in a new window when i click add button Error:'Unsupported context Type'
So, could you please help me to solve this?
Thank You.
The built-in MVC scaffolding doesn't support Linq to SQL -- you'll have to use Entity Framework instead. (Or don't use the scaffolding, build your own controller/action logic manually. Or use a scaffolding plugin that supports Linq to SQL.)
I got the same issue with EF. I am using the VS 2012.
Background:
The reason for my case was.. this auto generation process (Scaffolding) seems not recognize the partial class concept.
I used the model first approach and I have used inheritance with the entities.
Ex: entity “B” and “C” is inherited from “A”
So in my generated model class “DataModelContainer” which is inherited from “DbContext”,
There is no definition for “DbSet” and “DbSet”
i.e: the following two lines were not there
public DbSet<B> B { get; set; }
public DbSet<C> C { get; set; }
Generated “DataModelContainer” class I a partial class, so I completed the other part, using the concept of partial class. And this would be a problem for Scaffolding.
Solution
My workaround was, just removed the partial class I added manually. And added the definitions for “DbSet” and “DbSet” in to the auto generated class.
The problem with this solution is, I have to repeat the same thing when I regenerate the model classes.

Code first: does fluent api influence UI?

I'm reading a book written by Julie Lerman on Code First. According to the book, annotations and fluent api give the same result. Everything depends on the style of the developer.
I know that annotations allow both to configure how code first generate database objects and how MVC customize UI elements. Let's say I use [Required, MaxLength(50)]. The attribute will generate a NOT NULL, nvarchar (50) in the database. It also will validate the input for that field.
[Required, MaxLength(50)]
public string Name { get; set; }
What if I decide to use Fluent API to configure Code first. Am I still going to need annotations to influence UI elements or using fluent API is going to be enough?
EDIT
How about annotations, such as Display that serve only for UI purposes? Do they have equivalents? If not, Will I need to use annotaions?
[Display(Name = "Date of Birth")]
public DateTime BirthDate { get; set; }
Thanks for helping
Data Annotation is the simplest way of telling a class to enforce some validation rule. You can do the same thing with Fluent API as well. Some people like doing it by data annotations and some people like it by doing with fluent API
Reasons to like it with Data Annotations
1) Keep the validation info about my entity in one place along with the entity definition
Reasons to like it with Fluent API
1) Keep my entity clean. It will have only my property info. No validation info. Clean and simple POCO. I will write validation on the OnModelCreating method in my data context class.
You can not do all Fluent API things with Data Annotations way. the same way you don't have few Data Annotations attributes equivalant not present with Fluent API way ( Ex : HasMinLength) . HasMinLength is something we will for our Model validation which usually makes sense in the UI.
For the UI Model Validation, you can not use the Fluent API alone. Fluent API's major role is to look into the fluent configuration we writes and act when creating the Model(Database) from the entities. Remember we are overriding the OnModelCreating method to write our fluent API configuration. So for the UI Validation (of my ViewModel), I would use the DataAnnotation way and use fluent API if i want to define some thing related to my datamodel like Define a foreign key or Map this Entity to a Table with different name etc..
EDIT : As per the question edit,
You should make use of the Data Annotations in this case. If you are doing code first. You may remember that that entity is going to be your Database table ( of course you can tell EF to ignore /rename specific columns). In that case, I would keep my Entities clean and Create a ViewModel which i will use in my UI. I will add my DataAnnotations in my ViewModel to handle it. I may write some mapping code which maps data from ViewModel to Model and Model to ViewModel wherever necessary.
If your entity model classes are doubling as your viewmodel classes, AND you are using the default out of the box DataAnnotationsValidationProvider, then you would need the dataannotations attributes on the model properties to get validation.
However, you should not double your entity classes as viewmodel classes. Take for instance, a controller that needs to have a ReturnUrl property in its model. You wouldn't want this in your entity model / database. Because of differences like this between the View model and the Entity model, the 2 should really be separate (yet cohesive) layers in your application. You can make them cohesive using a library like AutoMapper.
This is one of the reasons I prefer the fluent API. If you stick to the fluent API, then you would never put any attributes on any entity model classes or properties. When it comes time to show, insert, or update data, you put the attributes on the viewmodel classes only.
Also, the [Required] attribute on an entity type performs validation during SaveChanges, whereas a [Required] attribute on a viewmodel performs validation during model binding.
According to Julie Lerman's book on DbContext, you do NOT need any additional annotations to your Fluent API configuration. The Name property will get validated by Validation API as if it had been configured with Data Annotations.
According to the same book, MaxLength and Required are the only validation attributes with fluent API conterparts.

Entity Framework 4.1 - Code First with existing Database, how to define classes, using Attributes or EntityTypeConfiguration? What is the difference?

I have been studying the EF for a short time and cant find the answer to this question.
I have existing database and I am using CodeFirst to create classes for the model.
What is the difference in using Attributes and EntityTypeConfiguration to define parameters of table columns?
Since the database already has defined foreign keys and unique constraints, and so on, how and where to implement the validation for a best and most fluid result for use in ASP.NET MVC3?
Is it better to implement Attributes and CustomValidation or to use TryCatch blocks to catch errors from db?
Does Validator.TryValidateObject(myModelObject, context, results, true); use validation rules defined only as Attributes or can it use rules defined in EntityTypeConfiguration?
Thank You
Get the Entity Framework Power Tools CTP1 and it will reverse engineer your database and create entities, and a full data mapping. This is different than Model or Database first in that it generates a fluent model rather than using an .edmx file. You can see exactly how it works then.
See the following article about how you can create your entity classes from existing database :
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx
Code generation templates will do the work for you, you don't need to write them if you have an existing db.
For validation, you can create new partial classes under the same namespace and put DataAnottations for your properties. Here is an example for you :
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace TugberkUgurlu.App1.DataAccess.SqlServer {
[MetadataType(typeof(Country.MetaData))]
public partial class Country {
private class MetaData {
[Required]
[StringLength(50)]
[DisplayName("Name of Country")]
public string CountryName { get; set; }
[Required]
[StringLength(5)]
[DisplayName("ISO 3166 Code of Country")]
public string CountryISO3166Code { get; set; }
[DisplayName("Is Country Approved?")]
public string IsApproved { get; set; }
}
}
}
-Since the database already has defined foreign keys and unique constraints, and so on, how and where to implement the validation for a best and most fluid result for use in ASP.NET MVC3?
These should happen via your generated model. Keys are automatically inferred. If you reverse engineer an existing database the attributes will be created for you. If not, there are basic rules that are followed. The entity framework will attempt to use an auto incrementing primary key for example unless you tell it otherwise via
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]
The relationships are already part of your model so there is your referential integrity, and the data annotations will define the validation rules.
-Is it better to implement Attributes and CustomValidation or to use TryCatch blocks to catch errors from db?
Implement attributes. Define your metadata classes with your attributes in them.
In addition you want to catch any db errors for anything else that is unexpected if your db has additional logic in there not defined in your model (try catch at some level should generally be used anyways for logging purposes_
-Does Validator.TryValidateObject(myModelObject, context, results, true); use validation rules defined only as Attributes or can it use rules defined in EntityTypeConfiguration?
As far as I'm aware only the attributes are used. I'm going to try to test this later though as I'd like a definite answer on this as well :)

MVC 3 - Entity Framework - Scaffolding - Validation issue

Im developing an MVC 3 application with Entity Framework and Im tring to use Scaffolding.
To solve "Type not mappedd issue" I've done the procedure found here. Everything now works fine.
Default validation is not working, required field are firing an exception instead of write something on ValidationSummary, so I want to add my custom validations using attributes.
The problem is that the solution about "type not mapped issue" has added 2 .tt files and a .cs file for each of my entities, these files are recreated each time my model (.edmx) is changed and saved so I cant put my Data Annotation Validator Attributes in those classes and either I cant create a new partial class with some properties because thay are already defined.
How can I do? May I have to move validation client-side using jquery? Or maybe there a workaround to add Data Annotation Validator Attributes to my entities, I prefer this way to have more visibility of my validations.
Thanks in advance
I've not used the DbContext generator, but have had similar issues with the POCO Generator. Assuming that the solution is similar:
Modify the T4 template that creates the entity classes to add an extra attribute to the class:
[MetadataType(typeof(CustomerMetaData))]
where "Customer" is the name of the entity.
Then, manually create MetaData classes for each of your entities. You can actually use a T4 template for that, too, if you want, but not have it run all the time.
The Metadata classes look like this...
public class CustomerMetaData
{
[StringLength(150, ErrorMessage="Maximum length is 150 characters.")]
[Required(ErrorMessage="CustomerName is required.")]
public virtual string CustomerName
{
get;
set;
}
public virtual Nullable<int> Type
{
get;
set;
}
// ... etc ...
}
As you can see, you attach the rules to the MetaData class, thus abstracting it from the generated entity class.

ASP MVC3 Database-first

I use the entity framework for application ASP MVC3. At first I using code-first approach. I created the classes and used attributes to validate the data field
public class Person
{
public int ID { get; set; }
[Required(ErrorMessage = "Name can not be empty")]
public string Name { get; set; }
}
But when using database-fitst, I do not know how to validate the datafields.
In this case class Person is automatically created. How to do validate of its data fields?
Here's my $0.02 worth. If you want to validate your model which has been generated by entity framework using the Database first approach then you have to make use of a concept called 'Buddy' class. I believe Scottgu has a great article on that. As you can see the model classes generated by Entity Framework are partial classes meaning to say you can also create your own partial class to hold the so called attributes or to describe the metadata of the generated model. These partial classes will then be combined to form one class at runtime. Please do check out ScottGu's blog
here: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
Hope this answers your question.
Hard to understand what exactly you mean, but I can recommend reading this.
The concept of Code First is simple:
You create the classes. In your classes you can use the Required attribute just like you would with the normal Entity Framework
EFCodeFirst creates the database tables for you.

Resources