0

i have a problem with my mvc3 application, i need to create some Validation stuff. but i dont have a normal model class because i have used EF with the database first approach.

i can not just open the class and write something like:

[Required]
[StringLength(10)]

how to solve this problem?

1 Answer 1

2

You could use the MetadataType attribute. So let's suppose that EF spit at your face the following class which you cannot modify:

public partial class Foo
{
    public string Bar { get; set; }
}

Now you could extend it since it is a partial class:

[MetadataType(typeof(FooMetadata))]
public partial class Foo
{
}

and then define the metadata:

public class FooMetadata
{
    [Required]
    [StringLength(10)]
    public string Foo { get; set; }
}

Or, simply throw data annotations away and use a real validation framework such as FluentValidation.NET (which I use and strongly recommend) allowing you to express complex validation rules on your models in a fluent manner, has an excellent integration with ASP.NET MVC and also allows you to elegantly unit test your vaildation logic in isolation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.