2

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?

4 Answers 4

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I was afraid of that, but thanks anyway. I dont know why ADO.NET does not just leave the field with default value binding alone when the property isnt set on the application side.
@Qin: Because you may want to place null value in this field.
By using DateTime.Now on the code side, it defeats the purpose to have the creation time populate by the database server.
@Qin: It does, but you want to change value on code side later, don't you? You can always call GetDate() from server and populate field.
1

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.

2 Comments

I think what Qin is saying is that he already has the binding setup but the Entity Framework is ignoring it
I know this, perhaps my question wasn't clear enough. It is just ADO.NET keep on overriding the default value by inserting 0001-01-01 00:00:00.0000000
1

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.

Comments

0

StoreGeneratedPattern= Identity or Computed does the trick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.