nobody
nobody

Reputation: 2759

C# ADO.NET inserting new rows with default values

I have this table in my database

Table Project
ProjectId (int), ProjectName (varchar(50)), ProjectCreationDate(datetime2(7))

ProjectId is the identity
ProjectName is non-null allowable with no default value
ProjectCreationDate has a default binding (sysdatetime())

I create a ADO.NET EDM and attempt to insert into the table


using (ProjectEntities context = new ProjectEntities()){
    Project p = Project{
        ProjectName = "ADO"
    };

    context.Projects.AddObject(p);
    context.SaveChanges();
}

The problem is the ProjectCreationDate column is populated with 0001-01-01 00:00:00.0000000 while I was expecting the current time that will be populated by the database itself.

I have other tables in my database with default value binding and the value will be changed later one. So setting StoreGeneratedPattern = "computed" isn't the solution I am look for.

Any ideas?

Upvotes: 2

Views: 2043

Answers (4)

lmestor
lmestor

Reputation: 1

StoreGeneratedPattern= Identity or Computed does the trick.

Upvotes: 0

Mike
Mike

Reputation: 11

If you always want the value to be set with sysdatetime() then you can make the "Setter" private in the entity model. The model won't try to populate the field and the default value supplied by the database will be populated in the table.

Upvotes: 1

Crimsonland
Crimsonland

Reputation: 2204

Sir LukLed is Correct or if you want Add Default Value or Binding in your table.

right click your table name(Table Project)
, choose Design
,Click on your Column Name(ProjectCreationDate) that you want to create default value
On Column Properties, click on Default value or binding then add input 
getdate().

It will populate ProjectCreationDate every time you will insert data.

Regards.

Upvotes: 1

LukLed
LukLed

Reputation: 31842

That is probably not what you would want to hear, but one of solutions is to define default values in constructor:

public partial class Project
{
    public Project()
    {
        ProjectCreationDate = DateTime.Now;
    }
}

Upvotes: 1

Related Questions