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

            Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

            Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

            How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page