What is the Entity Framework Core attribute equivalent to modelBuilder's HasDefaultValueSql?2019 Community Moderator ElectionUsing a custom attribute in EF7 (core) OnModelCreatingWhat is the difference between String and string in C#?What does the [Flags] Enum Attribute mean in C#?What is the best way to iterate over a dictionary?What are the correct version numbers for C#?How to know if an object has an attribute in PythonSelecting element by data attributejQuery how to find an element based on a data-attribute value?What is a NullReferenceException, and how do I fix it?How to get the data-id attribute?Entity Framework 5 Updating a Record

What is this tube in a jet engine's air intake?

I can't die. Who am I?

How do I increase the number of TTY consoles?

How to copy the rest of lines of a file to another file

Too soon for a plot twist?

Are these two graphs isomorphic? Why/Why not?

Is it appropriate to ask a former professor to order a book for me through an inter-library loan?

Would those living in a "perfect society" not understand satire

Idiom for feeling after taking risk and someone else being rewarded

Is there stress on two letters on the word стоят

Use Mercury as quenching liquid for swords?

What will happen if my luggage gets delayed?

Converting from "matrix" data into "coordinate" data

How do spaceships determine each other's mass in space?

Origin of the word “pushka”

Either of .... (Plural/Singular)

Is it a Cyclops number? "Nobody" knows!

Is divide-by-zero a security vulnerability?

The (Easy) Road to Code

I reported the illegal activity of my boss to his boss. My boss found out. Now I am being punished. What should I do?

Should we avoid writing fiction about historical events without extensive research?

School performs periodic password audits. Is my password compromised?

Having the player face themselves after the mid-game

Did Amazon pay $0 in taxes last year?



What is the Entity Framework Core attribute equivalent to modelBuilder's HasDefaultValueSql?



2019 Community Moderator ElectionUsing a custom attribute in EF7 (core) OnModelCreatingWhat is the difference between String and string in C#?What does the [Flags] Enum Attribute mean in C#?What is the best way to iterate over a dictionary?What are the correct version numbers for C#?How to know if an object has an attribute in PythonSelecting element by data attributejQuery how to find an element based on a data-attribute value?What is a NullReferenceException, and how do I fix it?How to get the data-id attribute?Entity Framework 5 Updating a Record










1















I want to use annotations for setting the default value for my properties in Entity Framework Core. The issue is that the database is not setting the default values so the value is not being passed down to the database layer.



I want to do something similar to modelBuilder's HasDefaultValueSql:



[DefaultValue("400")]
public int LengthInMeters get; set;


How do you convert the below code to attributes?



modelBuilder.Entity<Patient>().Property(c => c.LengthInMeters).HasDefaultValueSql("400");


Using default values by themselves doesn't work. I want to use attributes alone without having to mess with the migrations.



Problems: I've tried other methods with EF but Entity Framework Core doesn't have some items. Such as modelBuilder.Conventions nor AttributeToColumnAnnotationConvention nor CSharpMigrationCodeGenerator nor modelBuilder.Properties()










share|improve this question



















  • 3





    You can not set a default value using Data Annotations and By convention, a default value is not configured

    – NaDeR Star
    Mar 7 at 1:25












  • @NaDeRStar That is exactly what I am trying to replace with the attributes.

    – Demodave
    2 days ago















1















I want to use annotations for setting the default value for my properties in Entity Framework Core. The issue is that the database is not setting the default values so the value is not being passed down to the database layer.



I want to do something similar to modelBuilder's HasDefaultValueSql:



[DefaultValue("400")]
public int LengthInMeters get; set;


How do you convert the below code to attributes?



modelBuilder.Entity<Patient>().Property(c => c.LengthInMeters).HasDefaultValueSql("400");


Using default values by themselves doesn't work. I want to use attributes alone without having to mess with the migrations.



Problems: I've tried other methods with EF but Entity Framework Core doesn't have some items. Such as modelBuilder.Conventions nor AttributeToColumnAnnotationConvention nor CSharpMigrationCodeGenerator nor modelBuilder.Properties()










share|improve this question



















  • 3





    You can not set a default value using Data Annotations and By convention, a default value is not configured

    – NaDeR Star
    Mar 7 at 1:25












  • @NaDeRStar That is exactly what I am trying to replace with the attributes.

    – Demodave
    2 days ago













1












1








1


1






I want to use annotations for setting the default value for my properties in Entity Framework Core. The issue is that the database is not setting the default values so the value is not being passed down to the database layer.



I want to do something similar to modelBuilder's HasDefaultValueSql:



[DefaultValue("400")]
public int LengthInMeters get; set;


How do you convert the below code to attributes?



modelBuilder.Entity<Patient>().Property(c => c.LengthInMeters).HasDefaultValueSql("400");


Using default values by themselves doesn't work. I want to use attributes alone without having to mess with the migrations.



Problems: I've tried other methods with EF but Entity Framework Core doesn't have some items. Such as modelBuilder.Conventions nor AttributeToColumnAnnotationConvention nor CSharpMigrationCodeGenerator nor modelBuilder.Properties()










share|improve this question
















I want to use annotations for setting the default value for my properties in Entity Framework Core. The issue is that the database is not setting the default values so the value is not being passed down to the database layer.



I want to do something similar to modelBuilder's HasDefaultValueSql:



[DefaultValue("400")]
public int LengthInMeters get; set;


How do you convert the below code to attributes?



modelBuilder.Entity<Patient>().Property(c => c.LengthInMeters).HasDefaultValueSql("400");


Using default values by themselves doesn't work. I want to use attributes alone without having to mess with the migrations.



Problems: I've tried other methods with EF but Entity Framework Core doesn't have some items. Such as modelBuilder.Conventions nor AttributeToColumnAnnotationConvention nor CSharpMigrationCodeGenerator nor modelBuilder.Properties()







c# attributes entity-framework-core custom-data-attribute






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday







Demodave

















asked Mar 6 at 23:12









DemodaveDemodave

3,48242941




3,48242941







  • 3





    You can not set a default value using Data Annotations and By convention, a default value is not configured

    – NaDeR Star
    Mar 7 at 1:25












  • @NaDeRStar That is exactly what I am trying to replace with the attributes.

    – Demodave
    2 days ago












  • 3





    You can not set a default value using Data Annotations and By convention, a default value is not configured

    – NaDeR Star
    Mar 7 at 1:25












  • @NaDeRStar That is exactly what I am trying to replace with the attributes.

    – Demodave
    2 days ago







3




3





You can not set a default value using Data Annotations and By convention, a default value is not configured

– NaDeR Star
Mar 7 at 1:25






You can not set a default value using Data Annotations and By convention, a default value is not configured

– NaDeR Star
Mar 7 at 1:25














@NaDeRStar That is exactly what I am trying to replace with the attributes.

– Demodave
2 days ago





@NaDeRStar That is exactly what I am trying to replace with the attributes.

– Demodave
2 days ago












1 Answer
1






active

oldest

votes


















0














This is what I ended up doing, if someone has a cleaner not as intensive way of implementation let me know.



protected override void OnModelCreating(ModelBuilder modelBuilder)

foreach (var entityType in modelBuilder.Model.GetEntityTypes())

foreach (var property in entityType.GetProperties())

var memberInfo = property.PropertyInfo ?? (MemberInfo)property.FieldInfo;
if (memberInfo == null) continue;
var defaultValue = Attribute.GetCustomAttribute(memberInfo, typeof(DefaultValueAttribute)) as DefaultValueAttribute;
if (defaultValue == null) continue;
property.SqlServer().DefaultValue = defaultValue.Value;





I can set the default value in the database using the default value attribute



[DefaultValue("400")]
public int LengthInMeters get; set;





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55033666%2fwhat-is-the-entity-framework-core-attribute-equivalent-to-modelbuilders-hasdefa%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    This is what I ended up doing, if someone has a cleaner not as intensive way of implementation let me know.



    protected override void OnModelCreating(ModelBuilder modelBuilder)

    foreach (var entityType in modelBuilder.Model.GetEntityTypes())

    foreach (var property in entityType.GetProperties())

    var memberInfo = property.PropertyInfo ?? (MemberInfo)property.FieldInfo;
    if (memberInfo == null) continue;
    var defaultValue = Attribute.GetCustomAttribute(memberInfo, typeof(DefaultValueAttribute)) as DefaultValueAttribute;
    if (defaultValue == null) continue;
    property.SqlServer().DefaultValue = defaultValue.Value;





    I can set the default value in the database using the default value attribute



    [DefaultValue("400")]
    public int LengthInMeters get; set;





    share|improve this answer





























      0














      This is what I ended up doing, if someone has a cleaner not as intensive way of implementation let me know.



      protected override void OnModelCreating(ModelBuilder modelBuilder)

      foreach (var entityType in modelBuilder.Model.GetEntityTypes())

      foreach (var property in entityType.GetProperties())

      var memberInfo = property.PropertyInfo ?? (MemberInfo)property.FieldInfo;
      if (memberInfo == null) continue;
      var defaultValue = Attribute.GetCustomAttribute(memberInfo, typeof(DefaultValueAttribute)) as DefaultValueAttribute;
      if (defaultValue == null) continue;
      property.SqlServer().DefaultValue = defaultValue.Value;





      I can set the default value in the database using the default value attribute



      [DefaultValue("400")]
      public int LengthInMeters get; set;





      share|improve this answer



























        0












        0








        0







        This is what I ended up doing, if someone has a cleaner not as intensive way of implementation let me know.



        protected override void OnModelCreating(ModelBuilder modelBuilder)

        foreach (var entityType in modelBuilder.Model.GetEntityTypes())

        foreach (var property in entityType.GetProperties())

        var memberInfo = property.PropertyInfo ?? (MemberInfo)property.FieldInfo;
        if (memberInfo == null) continue;
        var defaultValue = Attribute.GetCustomAttribute(memberInfo, typeof(DefaultValueAttribute)) as DefaultValueAttribute;
        if (defaultValue == null) continue;
        property.SqlServer().DefaultValue = defaultValue.Value;





        I can set the default value in the database using the default value attribute



        [DefaultValue("400")]
        public int LengthInMeters get; set;





        share|improve this answer















        This is what I ended up doing, if someone has a cleaner not as intensive way of implementation let me know.



        protected override void OnModelCreating(ModelBuilder modelBuilder)

        foreach (var entityType in modelBuilder.Model.GetEntityTypes())

        foreach (var property in entityType.GetProperties())

        var memberInfo = property.PropertyInfo ?? (MemberInfo)property.FieldInfo;
        if (memberInfo == null) continue;
        var defaultValue = Attribute.GetCustomAttribute(memberInfo, typeof(DefaultValueAttribute)) as DefaultValueAttribute;
        if (defaultValue == null) continue;
        property.SqlServer().DefaultValue = defaultValue.Value;





        I can set the default value in the database using the default value attribute



        [DefaultValue("400")]
        public int LengthInMeters get; set;






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited yesterday

























        answered yesterday









        DemodaveDemodave

        3,48242941




        3,48242941





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55033666%2fwhat-is-the-entity-framework-core-attribute-equivalent-to-modelbuilders-hasdefa%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme