Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

c# - How to use the default Entity Framework and default date values

In my SQL Server database schema I have a data table with a date field that contains a default value of

CONVERT(VARCHAR(10), GETDATE(), 111)

which is ideal for automatically inserting the date into the new record when manually entering records in to the database.

The problem I have is that when using the Entity Framework and mapping the Date field, that the Entity Framework inserts a default value of DateTime.Min when the entity is instantiated.

I cannot map the Date field to a nullable DateTime, i.e. DateTime?, nor am I able to use either CONVERT or DateTime.Now.Today in the default value of the Entity Designer as it only accepts hard-coded constant values.

I can of course explicitly set the DateTime field in C# whenever the object is created, either explicitly in code, in the constructor of a partial class, or even during the saving changes event.

Are there any other ways of achieving what I want where the default value calculation stored in the database table is actually used instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create a partial class for your EntityObject, add a default constructor, and set default values in it.

    public partial class YourDBObject
    {
          public YourDBObject()
          {
               this._DateField = DateTime.Now;
          }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...