Entity Frameworks 4.0 Recipes

I am working though Entity Frameworks 4.0 Recipes. I love the concept and the examples look great. I started on page 20 with and simple and select from EF. Here is the first code sample:

1 static void InsertData() 2 { 3 using (var context = new EFRecipiesEntities()) 4 { 5 var poet =new Poet {FirstName="John", LastName="Milton"}; 6 var poem = new Poem {Title = "Paradise Lost"}; 7 var meter = new Meter{MeterName="Iambic PentameterXXXX"}; 8 poem.Meter = meter; 9 poem.Poet = poet; 10 context.Poems.AddObject(poem); 11 context.SaveChanges(); 12 } 13 } 14 15 static void ViewDataFromTables() 16 { 17 using (var context = new EFRecipiesEntities()) 18 { 19 var poets = from p in context.Poets select p; 20 foreach (var poet in poets) 21 { 22 Console.WriteLine("{0} {1}", poet.FirstName, poet.LastName); 23 foreach (var poem in poet.Poems) 24 { 25 Console.WriteLine("\t{0} ({1})", poem.Title, poem.Meter.MeterName); 26 } 27 } 28 29 } 30 } 31

Some initial thoughts:

The misuse of the keyword var – it is everywhere.

He is using poor variable names, for example, ā€œpā€

I would re-write his select query as so:

1 static void ViewDataFromTables() 2 { 3 using (var context = new EFRecipiesEntities()) 4 { 5 ObjectSet<Poet> poetQuery = from poet in context.Poets select poet; 6 foreach (Poet poet in poetQuery) 7 { 8 Console.WriteLine("{0} {1}", poet.FirstName, poet.LastName); 9 foreach (var poem in poet.Poems) 10 { 11 Console.WriteLine("\t{0} ({1})", poem.Title, poem.Meter.MeterName); 12 } 13 } 14 15 } 16 } 17

Also, check out something wicked cool (or dangerous) from EF. I changed the insert to have a Meter Name that is not already part of the Meter table. Instead of throwing a referential constraint error when the new value came in, EF silently added it:

image

And once I run this:

 

1 static void InsertData() 2 { 3 using (var context = new EFRecipiesEntities()) 4 { 5 var poet =new Poet {FirstName="John", LastName="Milton"}; 6 var poem = new Poem {Title = "Paradise Lost"}; 7 var meter = new Meter{MeterName="XXX"}; 8 poem.Meter = meter; 9 poem.Poet = poet; 10 context.Poems.AddObject(poem); 11 context.SaveChanges(); 12 } 13 } 14

Here are the post-Insert values:

image

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: