1

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))?

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.