Set default value in EF designer datetime

后端 未结 5 1654
终归单人心
终归单人心 2021-01-03 20:43

Trying to set the default value of a datetime field to take current time. In SQL\'s field designer i\'d use getdate(). What should i use in Entity Framework

相关标签:
5条回答
  • 2021-01-03 20:57

    Setting default values in Entity Framework 5 and 6 by changing T4 Template File

    Made below changes in .tt(template file) remove if condition at line 34

    34 if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any())
    35 {
    

    add

    59 OnCreated();
    60 }
    61
    62 partial void OnCreated();
    63 <#
    

    refer this image http://i.stack.imgur.com/DdlNB.png red means remove and green means add

    This will add constructor in all entity classes with OnCreated method.

    Like below

    public partial class Category
    {
        public Category()
        {
          this.Products = new HashSet<Product>();
          OnCreated();
        }
    
     partial void OnCreated();
     public int Id { get; set; }
     public string Name { get; set; }
    
     public virtual ICollection<Product> Products { get; set; }
    }
    

    Then create class file using same namespace that of Entities.

    public partial class Category
    {
       partial void OnCreated()
       {
          Name = "abc"
       }
    }
    

    refer below answer for more details https://stackoverflow.com/a/38882032/5475124

    0 讨论(0)
  • 2021-01-03 21:02

    Right click edmx, open with, choose xml editor, find "ProviderManifestToken" change from 2008 to 2005. Save.

    0 讨论(0)
  • 2021-01-03 21:03

    kidos for this answer although it didn't worked for me after setting StoreGeneratedPattern attribute value to Computed but setting StoreGeneratedPattern attribute value to Identity worked for me , i was setting default "Guid" to UserID of UNIQUEIDENTIFIER type

    0 讨论(0)
  • 2021-01-03 21:05

    Building upon RPM1984's answer:

    1. Select the field that has the default value,Created_On in my example, within your EDMX file
    2. Go to the Properties panel
    3. Select the StoreGeneratedPattern attribute
    4. Then change the value to Computed

    EDMX to Properties panel

    0 讨论(0)
  • 2021-01-03 21:23

    Set 'StoredGeneratedPattern' to Computed against the field in the EDMX.

    You still need the default value in SQL Server though, the above setting will ensure EF honour's that.

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