Dima Railguner
Dima Railguner

Reputation: 173

How To Insert NULL Into DB if input text is empty

I'm trying to pass a HTML form to the server using AJAX (POST). That form contains multiple textfields. If these fields are empty, the controller receives values like field1="", field2="", field3="". Then I try to add values to the database (using EntityFramework 4.1) like this:

NewObject newobject = new NewObject { _field1 = field1, _field2 = field2, _field3 = field3};
myDBContext.NewObjects.Add(newobject);
myDBContext.SaveChanges();

How can I make it so that the empty strings are stored as NULL in the db?

The only thing that comes to mind:

f1 = (field1!= "") ? field1 : null;
f2 = (field2!= "") ? field2 : null;
f3 = (field3!= "") ? field3 : null;
NewObject newobject = new NewObject { _field1 = f1, _field2 = f2, _field3 = f3};
myDBContext.NewObjects.Add(newobject);
myDBContext.SaveChanges();

Are there more nice solutions (at any level (EntityFramework, using Data annotations, Sql Server))?

Upvotes: 1

Views: 1349

Answers (2)

nerdybeardo
nerdybeardo

Reputation: 4685

You can create an extension method.

public static class StringExtensions {
    public static string NullIfEmpty(this string text) {
        return string.IsNullOrEmpty(text)? null : text;
    }
}

Then just call the method

NewObject newobject = new NewObject 
                     {
                         _field1 = field1.NullIfEmpty(),
                         _field2 = field2.NullIfEmpty(),
                         _field3 = field3.NullIfEmpty()
                      };
myDBContext.NewObjects.Add(newobject);
myDBContext.SaveChanges();

Upvotes: 0

LazyTarget
LazyTarget

Reputation: 879

You can use the DBNull.Value to set null values when using Sql Server. And with Entity Framework I think it sets it to null in the db if the value is null.

You could shorten your code a bit.

NewObject newobject = new NewObject 
                     {
                         _field1 = (field1=="") ? null : field1,
                         _field2 = (field2=="") ? null : field2,
                         _field3 = (field3=="") ? null : field3
                      };
myDBContext.NewObjects.Add(newobject);
myDBContext.SaveChanges();

Upvotes: 3

Related Questions