Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default values in Entity Framework 6 (Database First)

Background: I’m beginning a project to convert a web application using Linq2Sql to use Entity Framework (v6) instead. I have a lot of experience with L2S, but I’m brand-new to EF. Since our application and its database already exist, we’re using the “Database First” approach. Also, the database is evolving, so we’re making changes in the schema and the model is updated from the revised database, which regenerates code for the EF model each time.

For many of our entities (database tables), we set default values in our code whenever an entity is constructed. In Linq2Sql it’s easy: define a partial class for the entity, and add a method to the class like this:

partial void OnCreated() { SomeProperty = SomeDefaultValue; }

Whenever Linq2Sql constructs a new entity object, it calls the OnCreated() method you define, and the default values are set as desired. It works great.

The Problem: In EF, I don’t see a way to do this in a Database First scenario.

  • If I modify the model code generated by EF, the model code is overwritten whenever we update the model after a database revision.

  • If I define a partial class for the entity in a separate file and define a constructor, the compiler complains that the constructor is already defined.

  • There doesn’t seem to be any support for something like L2S's OnCreated() method, either.

Any suggestions?

EDIT: Thanks everyone for the helpful comments, but I think I need to point out an important consideration: My goal is to use the database-first approach and stick with it, rather than switching to code-first. When the database schema changes over time I want the EF Designer (or POCO Generator or whatever tools) to update my EF entity classes to match. All without losing my additions to initialize class properties when the class is constructed in the application. This is easy in Linq2Sql, but I just don’t see a way to accomplish this in EF database-first. All suggestions are welcome!

like image 988
Sandy Gettings Avatar asked Feb 06 '23 07:02

Sandy Gettings


1 Answers

1 . Open .edmx file

2 . Select the field that has the default value and go to the properties

3 . then select StoreGeneratedPattern

4 . then change the value to Computed

i think it's worked.

like image 192
Yats_Bhavsar Avatar answered Feb 08 '23 17:02

Yats_Bhavsar