Set a constraint for minimum int value

c# ef-code-first ef-fluent-api entity-framework

Question

The Repository pattern is what I'm using. In order to prevent prices from being zero, I have an entity called Product and I want to specify the minimum value for price. Is it possible to build it into a class called EntitytypeConfiguration?

My course on product configuration

 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
4
2/24/2015 11:56:41 PM

Accepted Answer

Implementing IValidatableObject on your entity will enable server-side validation. If you are using MVC, add the data annotation to your view model for client-side validation. Additionally, you can add a database constraint by executing the Sql() method in a migration to add the check constraint.

1
2/22/2015 9:47:23 AM

Popular Answer

You cannot implement that constraint using EF settings, but you may instead use thecheck You can apply data annotations to the model directly, as shown in here, or indirectly, as shown in then post.

the following

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

That won't matter if you're using a view model, though, as those validations are only used when an ASP.NET object is created (typically when creating an instance from a web request into a controller). Since you don't have to abide by the attributes when creating an instance, you must use a custom getter and setter in place of auto-properties if you want to firmly validate it.

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;
        }
    }
}

As long as the database doesn't contain any erroneous data, this will function well with EF.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow