1

I have a Profile class that I'm trying to save to the database (MS SQL). In the database the fields are listed as 'NOT NULL'. The default/initial entry is going to be empty strings (string.empty).

I figured empty strings wouldn't fail for NULLs but it seems that EF is trying to pass them as NULL. Is that the case?

Here's some of the model class:

[Required]
public string Password { get; set; }

public string PasswordSalt { get; set; }

[Required]
[Display(Name = "Security Question")]
public string SecurityQuestion { get; set; }

[Required]
[Display(Name = "Security Answer")]
public string SecurityAnswer { get; set; }

That's the model. Here's the code that tries to set the data, using r as DataRow:

newProfile = new Profile
{
    Salutation = r["Salutation"].ToString(),
    FirstName = r["FirstName"].ToString(),
    MiddleName = r["MiddleName"].ToString(),
    LastName = r["LastName"].ToString(),
    Biography = r["Biography"].ToString(),
    Password = string.Empty,
    PasswordSalt = string.Empty,
    SecurityQuestion = string.Empty,
    SecurityAnswer = string.Empty,
    EnteredDate = DateTime.Now,
    LastUpdatedDate = DateTime.Now,
    RecordVersion = StaticTools.RecordVersion(),
};

_db.Profile.Add(newProfile);
try
{
    _db.SaveChanges();
}
catch (Exception ex)
{
    throw ex;
}

So, when we try SaveChanges() it fails with a DbValidationError, for Password, SecurityQuestion, SecurityAnswer.

"The Security Question field is required."

(Of course, we will not even check an empty password for login, the user will have to follow a registration email and set one.)

M Kenyon II
  • 4,136
  • 4
  • 46
  • 94

2 Answers2

2

By default the RequiredAttribute does not allow empty strings. You can override this behavior by setting the AllowEmptyStrings property to true.

[Required(AllowEmptyStrings = true)]
public string Password { get; set; }

public string PasswordSalt { get; set; }

[Required(AllowEmptyStrings = true)]
[Display(Name = "Security Question")]
public string SecurityQuestion { get; set; }

[Required(AllowEmptyStrings = true)]
[Display(Name = "Security Answer")]
public string SecurityAnswer { get; set; }
shf301
  • 31,086
  • 2
  • 52
  • 86
0

you have "Required" tags on your security question/answer properties. Required needs to not be empty string to pass a required check.

Remove the [Required] tags and that should alleviate your immediate issue.

From RequiredAttribute

The RequiredAttribute attribute specifies that when a field on a form is validated, the field must contain a value. A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters.

Kritner
  • 13,557
  • 10
  • 46
  • 72