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 (开发者_如何学CProjectEntities 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?
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;
}
}
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.
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.
StoreGeneratedPattern= Identity or Computed does the trick.
精彩评论