Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework code first add constraint for positive numbers

I need to add constraint only for positive number (0-...) and restrict numbers as (...-1).

CreateTable(
   "dbo.Drinks",
   c => new
   {
       Id = c.Int(nullable: false, identity: true),
       Name = c.String(),
       ImageUrl = c.String(),
       Price = c.Int(nullable: false),
       Count = c.Int(nullable: false)
   })
   .PrimaryKey(t => t.Id);
   //.Constraint ???

Something like 'unsigned' in MS SQL. Thank you.

like image 737
ovasylenko Avatar asked Dec 29 '16 14:12

ovasylenko


2 Answers

Entity Framework fluent configuration doesn't currently support min or max value settings, just length.

You can, though, implement validation like this, throught annotations:

[Range(1, int.MaxValue, ...)]
int YourInt{ get; set; }

But this will only incur in validation during save, not the actual constraint being added to the database as it would with the fluent configuration / migration.

PS

I love Entity Framework migrations but I only use it during development until the first release. It's a huge time saver until you actually ship your product. After that, I usually fine tune the database myself, including indexes and constraints, and drop using EF migrations altogether.

Databases should be clinically adjusted in production because they're usually one the most (if not the most) important factors in performance and optimization. And unfurtunately EF migrations don't give you all the flexibility you need, even though it covers the most important use-cases.

like image 120
André Pena Avatar answered Nov 10 '22 21:11

André Pena


Maybe with a Range Dataannotation:

[Range(0.0, Double.MaxValue)]

Only values over 0 is what you are looking for, aren't you?

like image 44
Carlos Avatar answered Nov 10 '22 21:11

Carlos