Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

后端 未结 21 1345
终归单人心
终归单人心 2020-11-29 22:53

Does any one know how I can specify the Default value for a DateTime property using the System.ComponentModel DefaultValue Attribute?

for example I try this:

相关标签:
21条回答
  • 2020-11-29 23:16

    Simply consider setting its value in the constructor of your entity class

    public class Foo
    {
           public DateTime DateCreated { get; set; }
           public Foo()
           {
               DateCreated = DateTime.Now;
           }
    
    }
    
    0 讨论(0)
  • 2020-11-29 23:18

    In C# Version 6 it's possible to provide a default value

    public DateTime fieldname { get; set; } = DateTime.Now;
    
    0 讨论(0)
  • 2020-11-29 23:20
    public DateTime DateCreated
    {
       get
       {
          return (this.dateCreated == default(DateTime))
             ? this.dateCreated = DateTime.Now
             : this.dateCreated;
       }
    
       set { this.dateCreated = value; }
    }
    private DateTime dateCreated = default(DateTime);
    
    0 讨论(0)
  • 2020-11-29 23:21

    There's no reason I can come up with that it shouldn't be possible to do through an attribute. It might be in Microsoft's backlog. Who knows.

    The best solution I have found is to use the defaultValueSql parameter in the code first migration.

    CreateTable(
        "dbo.SomeTable",
        c => new
            {
                TheDateField = c.DateTime(defaultValueSql: "GETDATE()")
            });
    

    I don't like the often reference solution of setting it in the entity class constructor because if anything other than Entity Framework sticks a record in that table, the date field won't get a default value. And the idea of using a trigger to handle that case just seems wrong to me.

    0 讨论(0)
  • 2020-11-29 23:22

    I also wanted this and came up with this solution (I'm only using the date part - a default time makes no sense as a PropertyGrid default):

    public class DefaultDateAttribute : DefaultValueAttribute {
      public DefaultDateAttribute(short yearoffset)
        : base(DateTime.Now.AddYears(yearoffset).Date) {
      }
    }
    

    This just creates a new attribute that you can add to your DateTime property. E.g. if it defaults to DateTime.Now.Date:

    [DefaultDate(0)]
    
    0 讨论(0)
  • 2020-11-29 23:25

    How you deal with this at the moment depends on what model you are using Linq to SQL or EntityFramework?

    In L2S you can add

    public partial class NWDataContext
    {
        partial void InsertCategory(Category instance)
        {
            if(Instance.Date == null)
                Instance.Data = DateTime.Now;
    
            ExecuteDynamicInsert(instance);
        }
    }
    

    EF is a little more complicated see http://msdn.microsoft.com/en-us/library/cc716714.aspx for more info on EF buisiness logic.

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