Last active
December 11, 2015 03:38
-
-
Save driscollwebdev/4539186 to your computer and use it in GitHub Desktop.
A better example of parsing and saving an object from JSON using the Single Responsibility Principle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void SaveFromJson(string jsonData, DbContext saveContext) | |
{ | |
Person person = GetFromJson(jsonData); | |
Save(person, saveContext); | |
} | |
public Person GetFromJson(string jsonData) | |
{ | |
try | |
{ | |
JavaScriptSerializer serializer = new JavaScriptSerializer(); | |
Person person = serializer.Deserialize<Person>(jsonData); | |
return person; | |
} | |
catch (ArgumentException argEx) | |
{ | |
//TODO: Handle this exception. | |
} | |
catch (ArgumentNullException argNullEx) | |
{ | |
//TODO: Handle this exception. | |
} | |
catch (InvalidOperationException badOpEx) | |
{ | |
//TODO: Handle this exception. | |
} | |
} | |
public void Save(Person person, DbContext saveContext) | |
{ | |
//This is just an example, but in prod code you'd need | |
//to make sure the entity doesn't already exist. | |
saveContext.Entry<Person>(person).State = System.Data.EntityState.Added; | |
saveContext.SaveChanges(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment