9

I am using the Repository pattern. I have a entity called Product and I want to set the minimum value for price to avoid zero prices. Is it possible to create it in a EntitytypeConfiguration class?

My product configuration class

 public class ProductConfiguration : EntityTypeConfiguration<Product>
 {
    public PlanProductConfiguration(string schema = "dbo")
    {
        ToTable(schema + ".Product");
        HasKey(x => new { x.IdProduct });

        Property(x => x.Price).HasColumnName("flt_price")
                              .IsRequired()
                              .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
   }
}
1
  • 1
    Unfortunately Fluent API support only MaxLength Commented Feb 21, 2015 at 20:56

3 Answers 3

7

If you want that constraint, you can't apply it via EF configurations, but you can apply it using the check see here on the database directly, or you can apply data annotations on the model see this SO post

Something like:

[Range(0M, Double.MaxValue)]
public double Price { get; set; }

However that won't make a difference if you are using a view model, as those validations are only applied on ASP.NET object creation(generally when creating an instance from a web request into a controller), so when you create an instance you don't have to obey the attributes, so if you want to firmly validate it you need to apply a custom getter and setter rather than auto-properties, something like:

public class Product
{
    private double _price;

    [Range(0M, Double.MaxValue)]
    public double Price {
        get {
           return _price;
        }
        set {
            if (value <= 0M) {
                throw new ArgumentOutOfRangeException("value",
                        "The value must be greater than 0.0");
            }
            _price = value;
        }
    }
}

This will work fine in EF, so long as you don't have invalid data in the database.

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

4 Comments

thanks! for the answer. The problem with data annotations is because I can't add other references in Domain Projects (that contains the entities). I gonna put the annotations in view model and the constraint directly in database. Thanks!
@Rodrigão: What's wrong with referencing System.Data.DataAnnotations.dll?
Hi @abatishchev, in my domain layer, that contains the entities, I don't think that is a best practice reference anything but System. I think i going to do the Colin way and tell the result. Thanks!
From conservative point of view, you can reference nothing but BCL DLLs. So you're fine. But actually you can reference anything you need to achieve your goals. It won't violate no principles or practices.
3

Rather than attributes-based validation I recommend to use Fluent Validation which:

  • uses expressive lambda expressions
  • can be kept in other assembly than the models
  • doesn't polute POCOs with unrelated code

Comments

2

For server side validation, implement IValidatableObject on your entity. For client-side validation, if you are using MVC, add the data annotation to your view model. And to add a database constraint, add the check constraint by calling the Sql() method in a migration.

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.