I am having problems with (2) fields when saving entities in my ASP.NET MVC4 application:
- phone
As you know, these fields will have special characters @
and -
typically. Here is my code from the controller using ValueInjecter to inject my model classes from the hydrated object via Model Binding:
public ActionResult Create(TestViewModel testViewModel)
{
using (var context = new MyEntities())
{
var person = new Person();
person.InjectFrom(testViewModel);
context.Person.AddObject(person);
context.SaveChanges();
}
}
The error I am getting is the following:
"String or binary data would be truncated. The statement has been terminated"
Ok on 1st glance you might say it's the size of the field in SQL, but the true issue is masqueraded because of those special charachters. If I enter the following for the fields:
phone: 11234565454514564561
email: blahblahblahblah
...then everything works.
However if I enter:
phone: 123-456-7890
email: test@wow.com
I get the error about the "String or binary data would be truncated". So I found a work-around but this seems completly unnecessary and probably the wrong way. If I explicitly map the values from the model bound object to the entity, using the C# escape characters, then my values will insert as shown below:
public ActionResult Create(TestViewModel testViewModel)
{
using (var context = new MyEntities())
{
var person = new Person();
person.InjectFrom(testViewModel);
//Explicitly map items preserving special charachters
person.EmailAddress = @testViewModel.EmailAddress;
person.Phone = @testViewModel.Phone;
context.Person.AddObject(person);
context.SaveChanges();
}
}
OK, so honestly I don't know where the culprit lies. Is this a MVC model binding issue, an Entity Framework issue, a C# deal, or ValueInjecter? I tried using annotations on my ViewModel properties to dictate the data types like Phone
and Email
but that didn't stop the issue. Only by being explicit in code by escaping those characters was a way to do it.
What am I doing incorrectly because I know fields like email and phone with special characters are saved off all the time to EF with MVC? What can I do to prevent having to sprinkle in those lines of code every time I have a value with a special character?
Thanks!!