0

SQL Server 2014 has a unexpected behavior, if you define a table with a default value, say an int such as as 6, then try to enter some non default columns, the SSMS responds with a message that the row has been entered but can't be read back and instructs you to complete the operation by running execution a query that isn't displayed. The operation is then completed. So it isn't a hard failure. However, at a higher level of abstraction, doing a SaveChanges() doesn't throw an error but writes a zero in the default column.

Here is a test table

CREATE TABLE [dbo].[TestDefaultInsert]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [ColumnWithDefault] INT NOT NULL DEFAULT ((6)), 
    [ColumWithUserdata] NVARCHAR(50) NOT NULL
)

Here is a test program:

class Program
{
    static void Main(string[] args)
    {
        using (var insertDbContext = new TestDefaultInsertionEntities())
        {
            var testDefaultInserts = insertDbContext.TestDefaultInserts;
            TestDefaultInsert di = new TestDefaultInsert();
            di.ColumWithUserdata = "SimpleData";
            //di.ColumnWithDefault = 8;     // zeros are inserted 
                                            // instead of the default value of 6
                                            // 8 inserted correctly 
                                            // when this line is uncommented. 
            insertDbContext.TestDefaultInserts.Add(di);
            insertDbContext.SaveChanges();

            foreach( var t in testDefaultInserts)
            {
                Console.WriteLine(t.ColumnWithDefault);
            }

            Console.ReadLine();
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user3594395
  • 181
  • 4
  • 7

1 Answers1

0

You should map your column ColumnWithDefault as Computed.

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string ColumnWithDefault{ get; set; }

OR

this.Property(t => t.ColumnWithDefault)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
Community
  • 1
  • 1
Backs
  • 24,430
  • 5
  • 58
  • 85