0

Hey all I am trying to assign a DBNull to an int class value as shown below:

namespace ETTData.Models
{
    public class CHeld
    {
        public class AdNo {
            public int RequestID { get; set; } = DBNull.Value;

            public string TLead { get; set; } = DBNull.Value;

            public DateTime RequestDate { get; set; } = DBNull.Value;
        }
    }
}

However, I get the error(s) of:

Error CS0029 Cannot implicitly convert type 'System.DBNull' to 'int' ETTData

Error CS0029 Cannot implicitly convert type 'System.DBNull' to 'string' ETTData

Error CS0037 Cannot convert null to 'DateTime' because it is a non-nullable value type

This also seems to be an issue when doing a DateTime and string varibles?

What would I be missing in order to get this to work?

Community
  • 1
  • 1
StealthRT
  • 10,108
  • 40
  • 183
  • 342
  • 3
    Why are you trying to assign a *database specific* type to your C# objects? Why is `null` not an option here? – DigiFriend May 10 '17 at 13:06
  • @DigiFriend I've read that **NULL** and **DBNull** are different from each other and if you are using varibles that are to be saved in a database then you need to use **DBNull** and not **NULL**. http://stackoverflow.com/questions/4958379/what-is-the-difference-between-null-and-system-dbnull-value – StealthRT May 10 '17 at 13:09
  • Yes, but *only* when you are saving to the DB. You can't assign `DBNull` to C# objects, as you have seen. – DigiFriend May 10 '17 at 13:10
  • 1
    I'd keep the C# properties as null. Then default the parameters to null in your DB procs that can be null and omit them from the SQL command parameter list if they equal null. – Wheels73 May 10 '17 at 13:11
  • What if there is no value, say for RequestID, and therefore it never sets it to anything if i dont have **= something** in the variable definition? – StealthRT May 10 '17 at 13:11
  • Well, try it and see if it works, cuz this approach isn't working at the moment. Are you using an ORM? – Mark C. May 10 '17 at 13:11

2 Answers2

1

Hi why are you trying to put db null value to your model class?

if you wan't your properties to receive null values you can use ? to make your types to nullable.

 public int? RequestID { get; set; }
 public string TLead { get; set; }
 public DateTime? RequestDate { get; set; }

Hope this helps.

Drew Aguirre
  • 375
  • 2
  • 15
1

You can only use DBNull with types that accept it as a valid value - the built in types do not - nor does any type you can create yourself - class/struct cannot be derived from DBNull - it is sealed, so can't be inherited from.

You need to use null for properties that can be nullable in the DB (and model struct types that cannot be null, such as int as nullables - int?).

When saving to the DB, check if these are null and if so, pass in DBNull to your database.

DigiFriend
  • 1,164
  • 5
  • 10