I come from the web forms world, and I'm learning MVC4 and Entity Framework 5 with a code-first approach. This is my first time using EF code-first and I'm having some trouble understanding what EF needs from me to be able to create/update a database.
I'm making a request to a RESTful service and deserializing the response into a DataContract. Ideally, I would like to be able to insert this DataContract into a database but I'm unsure how to generate the DbContext classes from the DataContract so EF can do it's thing.
The simplified version of the DataContract...
[DataContract]
public class MoviesDataContract {
[DataMember(Name = "total")]
public int Total { get; set; }
[DataMember(Name = "movies")]
public IEnumerable<Movie> Movies { get; set; }
[DataMember(Name = "link_template")]
public string LinkTemplate { get; set; }
}
[DataContract]
public class Movie {
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "title")]
public string Title { get; set; }
[IgnoreDataMember]
public int? Year {
get {
int i;
return int.TryParse(_year, out i) ? i : (int?)null;
}
set { _year = value.ToString(); }
}
[DataMember(Name = "year")]
private string _year { get; set; }
}
Here's an example of the DataContract usage...
using(var response = (HttpWebResponse)request.GetResponse()) {
var serializer = new DataContractJsonSerializer(typeof (MoviesDataContract));
var dataContract = (MoviesDataContract)serializer.ReadObject(response.GetResponseStream());
var model = new List<MovieViewModel>();
dataContract.Movies.ToList().ForEach(movie => model.Add(new MovieViewModel {
Title = movie.Title,
Year = movie.Year
}));
// MovieDbContext doesn't exist and it's what I'm unsure of how to generate
// I would think it would work something like this though (once created)
var db = new MovieDbContext();
db.Add(dataContext);
db.SaveChanges();
return View(model);
}
My Questions are...
- Is there a way to generate the
DbContextclasses from myDataContractor do I need to manually create them? - Is there a better approach to using (or really saving to a db) Deserialized data with Entity Framework (especially EF5)?
- Could someone provide a link that discusses EF (4 or higher) being used in conjunction with a DataContract? I think I may not have a complete grasp on how to effectively use EF5.