Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Bilal Haidar 144 posts 410 karma points
    Sep 15, 2016 @ 22:34
    Bilal Haidar
    0

    Using Constraint with custom data table - Cannot insert nulls

    Hi, I have a DTO where one of the properties has a Constraint of

        [Column("DateAdded")]
        [Constraint(Default = "getdate()")]
        public DateTime DateAdded { get; set; 
    

    When I try to insert a new record, I receive the exception:

    Cannot insert the value NULL into column 'DateAdded', table 'bumbraco.dbo.Comment'; column does not allow nulls. INSERT fails.
    The statement has been terminated. 
    

    Shouldn't the constraint automatically add "getdate()" for each newly record added?

    Thanks /Bilal

  • Michaël Vanbrabandt 863 posts 3348 karma points c-trib
    Sep 16, 2016 @ 06:34
    Michaël Vanbrabandt
    0

    Hi Bilal,

    you can add an attribute of type [NullSetting(NullSetting = NullSettings.Null)] which is used to allow nulls to your column.

    Hope this helps!

    /Michaël

  • Bilal Haidar 144 posts 410 karma points
    Sep 16, 2016 @ 07:34
    Bilal Haidar
    0

    This eliminates the exception, but still the "getdate()" is not taking effect. A null is now inserted.

    Does this Constraint Data Annotation work?

    Thanks

  • Michaël Vanbrabandt 863 posts 3348 karma points c-trib
    Sep 16, 2016 @ 07:48
    Michaël Vanbrabandt
    100

    Hi Bilal,

    The constraint is a string.

    Why not create a default constructor in your DTO where you assign the current date and time to DateAdded ?

    /Michaël

  • Bilal Haidar 144 posts 410 karma points
    Sep 16, 2016 @ 08:32
    Bilal Haidar
    0

    By the way, on SQL Management Studio, I was able to see that "Default Value or Binding" for the DateAdded column is actually "getdate()" but for some reason, it is not generating a new Date with every new entry.

    I will stick to pre-populating the field myself instead of relying on that.

    Thanks as usual Michael.

    /Bilal

  • Michaël Vanbrabandt 863 posts 3348 karma points c-trib
    Sep 16, 2016 @ 08:36
    Michaël Vanbrabandt
    1

    No problem Bilal, glad I could help you out!

    Have a nice day

    /Michaël

Please Sign in or register to post replies

Write your reply to:

Draft