Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert default value via EntityFramework

I have default constraint on my caption field in database. In web app if caption is empty NULL value passed to database and database returns exception because samo field it cannot be null (Caption varchar(50) NOT NULL).

So, what is easiest way to set some value ("" - empty string) or avoid to send NULL to database if value is really not provided. How I can set that in EntityFrameowrk, or maybe in data access layer...?

like image 423
user1810618 Avatar asked Mar 10 '26 04:03

user1810618


2 Answers

Just define property with empty string right after new entity creation. For example, within constructor. Example

Before update existing entity, you can check property for null:

entity.StringProperty = entity.StringProperty ?? String.Empty;
_db.SaveChanges();
like image 61
Dmitriy Startsev Avatar answered Mar 12 '26 16:03

Dmitriy Startsev


On my system MVC4 entity framework 5.0 I am using like this, (DataAnnotation)

[DefaultValue = DateTime.Now]

public DateTime MyDateTime { get; set; }

}

Or like this for others Types... string.Empty

like image 20
Lucas Rodrigues Sena Avatar answered Mar 12 '26 17:03

Lucas Rodrigues Sena