How to use the default Entity Framework and default date values

后端 未结 8 748
说谎
说谎 2020-12-15 23:53

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)
<
相关标签:
8条回答
  • 2020-12-16 00:20

    I had a similar problem using RIA Services with the Entity Framework. I was not able to set the value in the default constructor on the client side because the entity classes that are generated there already have an empty default constructor.

    The solution that I used was to implement the OnCreated partial method for the entity on the client by setting the required default value.

    0 讨论(0)
  • 2020-12-16 00:24

    This is really unfortunate. The answers referencing StoreGeneratedPattern are not a true solution, that doesn't allow you to ever set the value.

    All the team would have to do is something like this:

        [Required]
        [DefaultValue] // suggested attribute, whatever you want to call it
        public DateTime Created { get; set; }
    

    If a field is marked DefaultValue, then at EF's SQL generation time, properties with this attribute get checked if field == default(DateTime), if so, then simply omit that column from the generated code.

    0 讨论(0)
  • 2020-12-16 00:24

    The date field can be mapped to DateTime? only if the column is nullable in the database.

    0 讨论(0)
  • 2020-12-16 00:35

    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;
              }
        }
    
    0 讨论(0)
  • 2020-12-16 00:35

    You can use a database trigger, which, on insertion, checks if the inserted value is DateTime.MinValue (01.01.0001) and replaces it with the calculated value you desire. This MSDN article describes how to create a trigger.

    A little "flaw": with this solution you would have to store the new object to the database and read it back afterwards to update your object with the calculated value.

    0 讨论(0)
  • 2020-12-16 00:36

    I think the answer provided by lazyberezovsky on another SO question is the straight forward solution to this problem Entity Framework and Default Date

    0 讨论(0)
提交回复
热议问题