How to get EF 6 to handle DEFAULT CONSTRAINT on a database during INSERT

c# default-constraint entity-framework sql-server

Accepted Answer

The answer to your query lies in this passage:

What I am trying to do, therefore, is to get EF NOT to include the DEFAULT CONSTRAINT columns in its INSERT TSQL if I do not explcitly set values for them in the object.

You cannot accomplish that using Entity Framework. In inserts and updates, fields are either always computed or always present. However, you COULD write the classes so that they act as you have described. You must use backing fields or explicitly set the fields to their default values in the constructor.

public class DBUpdateTest
/* public partial class DBUpdateTest*/ //version for database first
{
   private _DefValue1 = 200;
   private _DefValue2 = 30;

   public DbUpdateTest()
   {
      DefSecond = DateTime.Second;
   }

   public DefSecond { get; set; }

   public DefValue1
   {
      get { return _DefValue1; }
      set { _DefValue1 = value; }
   }

   public DefValue2
   {
      get { return _DefValue2; }
      set { _DefValue2 = value; }
   }
}

You probably won't need to set the default in the database if you constantly insert using these classes, but if you occasionally insert using SQL from somewhere else, you'll need to also add the default constraint to the database.

5
4/15/2015 4:12:43 PM

Popular Answer

ZZZ_tmp


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