Database Reference
In-Depth Information
Listing 9-10. The Implementation of the Service Contract in Listing 9-9. (Be sure to add references to
System.Data.Entity and System.Security to this project.)
public class Service1 : IService
{
public void Cleanup()
{
using (var context = new EFRecipesEntities())
{
context.Database.ExecuteSqlCommand("delete from chapter9.comment");
context. Database.ExecuteSqlCommand ("delete from chapter9.post");
}
}
public Post GetPostByTitle(string title)
{
using (var context = new EFRecipesEntities())
{
context.Configuration.ProxyCreationEnabled = false;
var post = context.Posts.Include(p => p.Comments)
.Single(p => p.Title == title);
return post;
}
}
public Post SubmitPost(Post post)
{
context.Entry(post).State =
// if Id equal to 0, must be insert; otherwise, it's an update
post.PostId == 0 ? EntityState.Added : EntityState.Modified;
context.SaveChanges();
return post;
}
public Comment SubmitComment(Comment comment)
{
using (var context = new EFRecipesEntities())
{
context.Comments.Attach(comment);
if (comment.CommentId == 0)
{
// this is an insert
context.Entry(comment).State = EntityState.Added);
}
else
{
// set single property to modified, which sets state of entity to modified, but
// only updates the single property - not the entire entity
context.entry(comment).Property(x => x.CommentText).IsModified = true;
}
 
Search WWH ::




Custom Search