Derek
Derek

Reputation: 8630

EntityFramework 5 Validation

I'm looking for some advice. I'm working with EF 5 and I have a generic repository which handles all of the CRUD transactions with the database. This works fine, But i want to add a "Last Gap" safeguard to ensure that the entity is valid before the Data Access Layer attempts changes in the database.

Right before I do something like this :-

DataLayer.Create<TEntity>(entity);

I want to Validate the entity and throw an exception if the validation fails.

What would you guys use as the preferred method?

Upvotes: 0

Views: 868

Answers (3)

Colin
Colin

Reputation: 22595

Sometimes you have to go to the database to check whether inserting or updating an entity keeps the repository in a valid state - such as when you need to ensure the natural key is unique. That isn't currently handled by a data annotation or the Fluent API, although it has been discussed. See unique constraints in entity framework And this work item.

In the meantime, when you have to go to the database then DbContext will be involved somewhere, and DbContext has an Overridable method called ValidateEntity. See this article: Entity Framework Validation.

I put the code I use in another answer here

And more about how I've structured the validation in MVC here.

Upvotes: 2

OJ Raque&#241;o
OJ Raque&#241;o

Reputation: 4561

Using Data Annotations

You can use data annotations directly in your entity. With data annotations, EF will validate the property for you and if it is not valid, an exception will be thrown.

For example, if you want Name to be required, you can do something like:

public class Person
{
    [Required]
    public string Name { get; set; }

    // other members
}

Aside from validation, EF will also set the corresponding column to be not null instead of the default null for strings.

Using the Fluent API

If you don't want to litter your entities with data annotations, you can use the fluent API instead. Following is the equivalent of the above code:

public class MyContext : DbContext
{
    public DbSet<Person> People { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Entity<Person>().Property(p => p.Name).IsRequired();
    }

    // other members
}

My answer applies to EF Code First and may not apply for other workflows.

Upvotes: 2

Nano Taboada
Nano Taboada

Reputation: 4182

I wouldn't do validation at the DAL, but if you do, you might be interested in Validation with the Data Annotation Validators

Upvotes: 1

Related Questions