Json.Net
如果你学习Json.Net的话一定要看http://james.newtonking.com/json/help/index.html?topic=html/Samples.htm.
//Console.WriteLine("Please enter employee name");
//using (var db = new EFDatabaseFirstExample.EFDatabaseFirstDBEntities())
//{
// Company company = new Company();
// company.Name = "Mission Sky";
// company.Address = "Shenzhen";
// db.Companies.Add(company);
// Employee employee = new Employee();
// employee.Name = Console.ReadLine();
// employee.CompanyId = 1; //hard coded for demo purpose
// employee.Age = new Random(10).Next();
// db.Employees.Add(employee);
// db.SaveChanges();
//}
//Console.WriteLine("List of employees for company 1");
using (var db = new EFDatabaseFirstExample.EFDatabaseFirstDBEntities())
{
//get the company with ID = 1
//var company = (from c in db.Companies
// where c.Id == 1
// select c).SingleOrDefault();
//get the employee list for a company with a id = 1
//List<Employee> employees = company.Employees.ToList();
//display each item.
//foreach (var emp in employees)
//{
// Console.WriteLine(emp.Name);
//}
//Ado.Net Entity Framework support accidently added to json net
//An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
//Company company = db.Companies.Include("Employees").AsNoTracking().FirstOrDefault(c => c.Id == 1);
Company company = db.Companies.FirstOrDefault(c => c.Id == 1);
List<Employee> employees = company.Employees.ToList();
var serializerSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects };
//string json = JsonConvert.SerializeObject(company, Formatting.Indented, serializerSettings);
//Single Entity
Employee employeeEntity = db.Employees.FirstOrDefault(e => e.Id == 16);
string json = JsonConvert.SerializeObject(employeeEntity, Formatting.Indented,serializerSettings);
Employee employeeEntityObj = JsonConvert.DeserializeObject<Employee>(json);
Console.WriteLine(json);