I'm starting out with Entity Framewrok and I wrote the following simple sample code in a console application:
var post1 = new Post
{
PostTitle = "Post Title 1",
PostBody = "post Body 1",
Comments = new List<Comment>
{
new Comment{CommentAuthor="aravind",CommentBody="my first comment on post 1"},
new Comment{CommentAuthor="dimpu",CommentBody="my second Commment on post1"}
}
};
using (BlogEntites be = new BlogEntites())
{
foreach(Post post in be.Posts)
{
Console.WriteLine(post.PostTitle);
foreach (Comment comment in post.Comments)
{
Console.WriteLine("\t" + comment.CommentBody);
}
}
be.Posts.Add(post1); // post1 added in memory
be.SaveChanges(); // post1 added to DB
}
Console.WriteLine("press any key to continue...");
Console.ReadKey();
At first, I only had foreach
only on the posts and it worked fins and I had an output of all my posts.
Then I wanted to add the comments for each post so I've added another inner foreach - which if I was working with regular object (which to my understanding what ORM should be all about) that what I would have done....
But when running this code I'm getting inner exception:
There is already an open DataReader associated with this Command which must be closed first.
What am I not understanding here?
Thanks