Set a constraint for minimum int value

百般思念 提交于 2019-12-05 13:46:10

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.

tophallen

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.

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
octavioccl

I think what you want is a default value to your property. Unfourtunaly EF doesn't support setting default values in this moment. But, as a solution to your problem, you could create a constructor in your Product class an set the Price property with the minimum value that you want:

public class Product
{
   //...
   public Product
   {
      Price=1; //set your minimum price here
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!