Designing Repositories – Now I don’t feel so bad

Last week I was working with a client and we were creating some repositories to use with EF4 entities in her application. I felt kinda dumb because I couldn’t reason out where to put a method to retrieve “child” data, e.g., GetEmployeesForCompany(Company company). The method not only retrieves the employees but attaches them to the company, returning a graph.

My conundrum was should the method call go in to a repository who’s root was Company or the one with the root, Employee?

So I tweeted it but thanks to the 140 char limit, simplified the method to GetEmployeesForCompany(int companyId).

I got a lot of responses very quickly and they went back and forth which only confused me more.

Not until I put them all in this table (below) did I see that generally people were leaning towards returning it from employee.

But the best response was: “The answer is that it depends upon what you’re building – and how it would make most sense to aggregate 😉 i.e. aggregates only make sense in CONTEXT.” Thanks Mikey! 🙂

In the end, I think that I won’t fail by choosing one over the other. The important thing, which for me is also a great benefit of creating repositories, is the fact that I have put some thought into where the method goes and am making an explicit choice that works for me. And that is the lesson I can leave my client with, along with another which I repeated a few times – “I’m not the expert on this topic. We’re just taking baby steps (in the right direction) here.”

Company Employee

only make sense on the Company class, so I’d say Company.

Employee Repo!
I’d say Company Employee rep. Company is just a lookup parameter.
gsin u have emp and comp both as aggr. still, comp might restrict which emp it returns…so i’d put in comp Employee Repo!

I’d go with the company as the aggregate in this case.

I’d go with Employees and calling it GetByCompany(string companyId)
EmloyeeRepo.GetAllForCompany(123
 

I generally go with the convention that a rep only returns the type it is associated with but takes any type as a parameter

  so if reps other than employees returned employees, it would be hard to predict where all the places are that return employees
  your getting a collection of employees and not dealing with a Company object at all, I would put it in employee rep
  employee repository… it’s returning employees
  I’d say employee. You want a collection of employees, not a collection of companies. Think of it as a slippery slope.
 

Since you are getting employee’s, I would put it in the EmployeeRepository.

The Acknowledgements in Programming Entity Framework 2nd Edition

In a 900 page book, this was the only creative writing I got to do so I had some fun with it. 🙂

There are a lot of hyperlinks to push into here for the blog post, I will come back to that task later.

Acknowledgments


And now for the most rewarding writing task after completing over 800 pages of technical writing—thanking the Academy. My academy is a host of bright, generous, and dedicated geeks (and a few nongeeks) who have helped make this book the best it can be.

First nods go to the technical reviewers. These are the folks who were willing to read the book in its roughest format and provide feedback to help me make it more useful and comprehensible to you, the readers of the final version. The award for helping to keep me from exposing myself to humiliation over my nascent C# skills goes to Wesley Bakker, a Dutch developer who does code reviews for a living. I learned a lot from Wes and am grateful for his patience and kid-glove handling of my poor ego. I also had a number of EF and EF 4 newbies on board to help ensure that I didn’t make any leaps without bringing them along. You who are new to EF should thank them as well: Camey Combs, Suzanne Shushereba, Doug Holland, and John McConnell. Ward Bell’s brilliant architectural mind was displayed in comments that nearly exceeded my own text. He kept me honest and kept me thinking. Everyone should email Ward and beg him to write a book. I don’t care what the topic is. Ward has deep EF knowledge, as does Per Okvist, whose feedback was also invaluable. Two database gurus were enormously helpful: Bob Beauchemin and Anil Das. Their meticulous minds helped me in areas that reached much further than discussions about database specifics.

I also brought in some big guns to look at particular chapters in their area of expertise. Thanks so much to Greg Young, Bobby Johnson, Jarod Ferguson, and Mike Campbell for helping me with my education in persistence ignorance and related topics and for looking over the critical chapter on PI and testing to make sure that I had learned my lessons well. I was close, but they helped guide me where I had strayed. K. Scott Allen and Imar Spaanjaars, both ASP.NET gurus, provided some additional guidance and a read-through of a number of chapters.

And then there was the real editing—the organization and flow of the text. John Osborn, who was the editor on the first edition of this book, was engaged to edit this edition as well. It’s hard for me to express my gratitude for the incredible dedication  and expertise he provided. Even though I thought myself much more experienced this time around, John took every chapter and reorganized it, clarifying its focus and flow. He is an incredible editor and I was very lucky to have him work on my book again.

Along the way, of course, I had help from so many people at Microsoft on the Entity Framework team and beyond. There is no way I can list them all, but here’s my best shot (not in any special order): Danny Simmons, Elisa Flasko, Noam Ben-Ami, Diego Vega, Kati Iceva, Srikanth Mandadi, Alex James, Jarek Kowalski, Jeff Derstadt, Rowan Miller, Craig Lee, David Annesley-DeWinter, Adi Unnithan, Andrew Peters, Shyam Pather, and Tim Laverty. Forgive me if I’ve neglected to mention someone.

You’ll find that I have used (and recommended) a few additional tools throughout the book. The publishers generously provided me free licenses for which I’m grateful. The recommendations are because they are great tools, not because I didn’t have to pay for them. The tools include LINQPad, written by another O’Reilly author, Joseph Albahari; and ReSharper from JetBrains. ReSharper was my first line of defense for ensuring that my C# code wasn’t an embarrassment, while Wesley Bakker was my second. I learned so much from both of them. Entity Framework Profiler is an awesome tool for keeping track of what’s going on in your database when using Entity Framework. I also used two tools for producing images in this book. The first is Snagit from TechSmith, which was completely invaluable for capturing and editing screenshots. The second is Balsamiq Mockups, which enabled me to have a little fun creating mock-ups of application UIs in a number of chapters. Finally, thanks to Red Gate, a great company with many awesome tools. For this book, I used its .NET Reflector to inspect some assemblies,
and I’ve used their SQL Packager for creating a simple-to-install version of the sample databases for you to use.

My publisher has, as usual, provided great support for me. I had not one, but two editors—this is not the job of editing the book, but of counseling me and holding my hand throughout the process. Thanks to Laurel Ruma (who moved on to become O’Reilly’s über–Government 2.0 guru), and Mike Hendrickson who brings years of experience (not saying he’s old) for keeping me focused and helping me avoid being taken away in a funny white coat. I was also lucky to have Audrey Doyle as my copy editor again. She did an amazing job on the first edition, so I begged O’Reilly to contract her again. Lucky me, they did. (She is going to hate that last nonsentence; I dare you to leave it in, Audrey.)

If you read the Preface of my first book, you’ll be happy to know that this time around I have no heart-wrenching pet losses to report, so you can put away the tissues you may have prepared yourself with. In fact, we adopted a teenage Newfoundland dog named Sampson just as I began to write this edition. Thank goodness for his needed afternoon walks and his constantly entertaining personality, without which I’d have gone completely mad during the time I have been writing this book. You can meet this silly boy on my blog at http://thedatafarm.wpengine.com/blog/tags/Sampson.

Somehow I have managed to retain my patient husband, Rich Flynn, to whom I promised “don’t worry, never again” when I finished the first edition. He has just suffered through another year of spaghetti, dirty dishes, ravaged potato chip supplies, and having to cede a little more space in bed as my waistline expanded thanks to my life in the computer chair (and all those potato chips).

And finally, thanks to all of the incredible support that has come from the .NET community. I’m very proud of the first edition of the book, and each private “thank you” or complimentary public review on places like Amazon.com and your blogs has meant so much to me. This truly kept me going through what my Twitter followers know only too well was an arduous process in writing this second edition.

Oh, and to anyone who gave me chocolate…thanks!

Modified Description of Adding Inheritance into T4 Template from Chapter 18

This is in reference to Programming Entity Framework 2nd Edition

When I originally wrote the directions for modifying the T4 template in Chapter 18 (Using POCOs and Self-Tracking Entities in WCF Services), I was working with the “almost” RTM version of the Microsoft’s POCO T4 template. Since my modified template continued to work after RTM, I never thought to revisit that text and discovered yesterday that it doesn’t follow the current version of the template and therefore the instrux are unclear & confusing.

My discovery did not come from a reader but was made when I was working with a client and wanted to make that same modification in her template.

When I originally wrote that description I was borrowing some code from the EntityObject template that had a dependency on a variable called ModelNamespace. But in the newer version of the POCO template, that variable is no longer used.

Here are the modified paragraphs and links to the templates that you can download from the book’s website.

read more at : http://learnentityframework.com/LearnEntityFramework/errata/modified-description-of-adding-inheritance-into-t4-template-from-chapter-18/

Current Presentation Submissions for Vermont Code Camp 2

Vermont Code Camp 2 is Saturday Sept 11, 2010 in Burlington, Vermont.

We will be taking submissions for presentations through Sunday August 23rd.

Below is a list of the current abstracts submitted for the event.

We can fit more talks in during the day since we have 4 rooms so if you want to submit go to http://vtcodecamp.eventbrite.com.

Last year (our first) we had 85 attendees and expect even more this year. We’ve got lots of sponsors providing breakfast, lunch, books, software license and more!

Visit www.vtdotnet.org/codecamp for more info or go right to http://vtcodecamp.eventbrite.com to register as an attendee and/or submit your own session ideas!

_________________________________________________________________________________________________

Lambdas in C# and VB.NET using Visual Studio 2010
They can be used everywhere a delegate is needed, they’re handy and very sexy… They’re lambdas and if you already know what lambdas are then let me show you a few things you can do with them! Join me for a short introduction to the concept of lambdas and then explore spicy lambda examples that will show you more on their potential!

Get a handle on your build process
The choice of tools and processes surrounding your application deployment process can have major impacts on development time, deployment speed, and disaster recovery. This session will focus on dealer.com’s migration to Git, Maven, Hudson, and a new branching strategy for consistent, repeatable, speedy builds.

Silverlight and you – The best relationship you’ve ever had
With the release of Silverlight 4 more and more developers are looking to develop in Silverlight, especially with the introduction of Windows Phone 7. In this presentation anyone starting out, or even currently developing with Silverlight, will learn important information regarding this development platform, as well as look into how to create data-driven applications with Silverlight.

Building Cloud-Native Applications with Windows Azure
Cloud computing is here to stay, and it is never too soon to begin understanding the impact it will have on application architecture. In this talk we will discuss the two most significant architectural mind-shifts, discussing the key patterns changes generally and seeing how these new cloud patterns map naturally into specific programming practices in Windows Azure. Specifically this relates to (a) Azure Roles and Queues and how to combine them using cloud-friendly design patterns, and (b) the combination of relational data and non-relational data, how to decide among them, and how to combine them. The goal is for mere mortals to build highly reliable applications that scale economically. The concepts discussed in this talk are relevant for developers and architects building systems for the cloud today, or who want to be prepared to move to the cloud in the future.

Demystifying Cloud Computing and Windows Azure
Introducing the key concepts around Cloud Computing, including specifics around Microsoft’s Windows Azure cloud platform. The goal is to demystify the cloud by answering questions such as the following:- What is Cloud Computing? – Why should I care about it? – How do I take advantage of the cloud?

Android and WCF Services
So the sales manager walks into your office with his bright shiny Droid 2 and sayshis golf buddy showed him an app on his smarthphone accessing his company’s salesdashboard and wants you to do the same thing. Only problem is his buddy’s phone is an iPhone! Are you hosed? Not at all. Android has great support for consuming WCF services whether via DTO’s, RESTful, or OData. You can use a third-party library toserialize/deserialize data that’s almost as easy as Visual Studio’s "Add ServiceReference" or for maximum control and flexibility you can parse out the XML or JSONyourself. In this talk I’ll show you how to build an Android app that talks to WCF services for a hypothetical sales manager’s dashboard.

Introduction To Android Development
Interested in mobile development but don’t want to buy a Mac and don’t want to wait until Windows Phone 7 ships? Then you should take a look at Google Android.With over 160,000 device activations per day and dozens of devices from everycarrier Google Android is the fastest growing smartphone segment. And it’s very easy to get started. In fact, if you know C# or Java and have experience withXAML you already know more about Android development than you think. In this talk you’ll get an introduction to the tools necessary to get started and demonstrations of simple Android applications.

An Introduction to Redis
Redis is an extremely fast, full-featured key-value store. It makes an excellent complement to traditional SQL storage solutions for operations that require greater load tolerance or more speed.This session will cover installation and setup, basic and more advanced commands, and several real-world examples of Redis being used in production.

Project "Dallas" – Data for the Cloud
Project "Dallas" is Microsoft’s Data-as-a-Service offering, providing a common, and low-friction approach to a growing number of data sets from the Associated Press, NASA, the UN, and elsewhere. Use of the OpenData (or OData) specification enables applications written in practically any language to create mash-ups limited only by your imagination. Implemented on Microsoft’s Windows Azure platform, project "Dallas" also serves as a real-world use case of cloud computing.

Windows Phone Development with Silverlight
Microsoft’s upcoming entry into the new-generation smart-phone market features Silverlight as the platform for application development. This presentation will go over the fundamentals of using Silverlight to develop rich, interactive applications for this emerging platform.

Creating Business Applications with Silverlight 4
Silverlight’s ability to translate existing .Net development skills to the development of Rich Internet Applications makes it a powerful tool for developing cross-browser, cross-platform Line of Business Applications. This presentation will focus on using Silverlight and related technologies to access, present, and manipulate distributed business data.

MS Business Intelligence Fundamentals: Developing OLAP Cubes in SSAS 2008 R2
This session focuses on the OLAP functionality of SQL Server Analysis Services 2008 R2, exploring the process of developing basic SSAS cubes and dimensions. You will learn how to extend the Unified Dimensional Model (UDM) with KPIs, actions, translations, and perspectives. And finely process and deploy SSAS database and objects into MS SQL Server 2008. We will learn how to: • Create Data Sources and Data Source Views • Create and Modifying SSAS Cubes • Create and Modifying Dimensions • Create Measure Groups and Measures • Create KPIs, Actions, Translations, and Perspectives • Process and Deploy SSAS Databases and Objects

What’s New in the .NET Framework & Languages  (abstract coming)

Visual Studio Tips and Tricks (abstract coming)

Managed Extensibility Framework (MEF) (abstract coming)

Like LINQ and lambdas? You’ll love F#! 
If you’ve already spent time wrapping your head around the use of lambdas in LINQ, find out how to use that knowledge to make the full leap into functional languages and reap the rewards functional languages have to offer you. This stuff is Zen, dude!

Sampson on Sunset Rock

This past week, my niece came to visit from Massachusetts and I had a mini-vacation. One of the many activities we did was take a hike and because it was cool-ish, we brought Sampson along. Here we are high up in the Green Mountains enjoying views of the Adirondacks. Mr. Muddy-Paws had found a nice cool pool of mud on the way up. Sampson has been with us for just over a year now. He’s 2 1/2 years old and turning into a wonderful dog.

sampson hiking with bonnie July 2010

Upcoming Entity Framework Events

I’ve started working on my fall calendar…here’s what’s going on so far.

 

Cleveland, Ohio, August (okay not quite fall…)

Tuesday August 10: Cleveland .NET SIG (INETA User Group Event) http://www.bennettadelson.com/netsig.aspx

 

Vermont, September

Saturday Sept 11: Vermont Code Camp 2!  www.vtdotnet.org/codecamp

 

NYC, September

Monday, Sept 27: Entity Framework Full Day Firestarter, Microsoft Offices, Free. Details & Registration forthcoming…

 

London, England, October

Thursday Oct 21: I am leaving this day open and would love to do a full day of EF mentoring with *your* company’s dev team. Contact me!

Friday Oct 22: Full Day Hard Core EF 4 Workshop. Probably around £300-£400 for the day. Details & Registration forthcoming…

Saturday Oct 23: Full Day, multi-speaker event at Microsoft including something on intro EF4 by moi. Free! Details & Registration forthcoming…

 

The Netherlands, October

Mon&Tue, Oct 25 & 26: SDN Conference http://www.sdn.nl/SDN/SDNEvent/SDNConference2010/tabid/162/Default.aspx

 

Las Vegas, November

Mon-Thurs, Nov 1-4: DevConnections  http://devconnections.com/

Vermont IT Jobs: RFP for 3-6 month project, C# Programmer w/NHibernate exp

Request for Proposal
Application Development Support
7/19/2010

The Vermont Energy Investment Corporation (VEIC), a non-profit corporation, requests
proposals for application development support to be completed and presented to VEIC by
7/26/2010.

Electronic submissions of the proposals are welcome and encouraged. Please send those to
jfishelman@veic.org. Written proposals and resumes (including attachments) should be no
longer than 4 pages.

Vermont Energy Investment Corporation
Vermont Energy Investment Corporation (VEIC) was founded in 1986 and is a non-profit
corporation that provides energy conservation and renewable energy programs and projects,
nationally and internationally. VEIC includes one division that administers the Efficiency
Vermont (EVT) contract with the state of Vermont. This program is funded by electric
ratepayers in the form of a surcharge on their electric bills. VEIC also has a separate division
that provides consulting, program development, evaluation, viability analyses, and other expert
technical services nationally. VEIC employs over 180 employees in four states, the majority of
whom are in Vermont. Further information about VEIC can be found on our website:
http://veic.org.

Scope of work
VEIC requires the assistance of an experienced C# programmer to assist us in the development
of our central line of business application(s). This work requires a high degree of proficiency in
object-oriented programming using industry standard best practices including test driven
development. Candidates with experience with NHibernate and dependency injection
frameworks preferred.

Work is expected to last between 3 and 6 months.

The selected candidate will work as part of our application development team and under the
direct supervision of our Lead Software Engineer.

Responses
Responses should include the credentials and experience of the persons who would be
designated to conduct the required services.
References
Please supply at least three (3) references who have used your professional services for a
similar project. Include a contact name, address, and a contact phone number.

VEIC will conduct follow up interviews with the person(s) who would be providing the
required services to further discuss experience and expertise.
Proposal selection will be qualifications-based. VEIC will intend to negotiate contract terms
with the most qualified vendor. If unsuccessful, VEIC would intend to then negotiate with the
next most qualified vendor, until reaching satisfactory contractual arrangements. VEIC
reserves the right to not award a contract should none of the proposals adequately address the
requirements outlined in the RFP.

Proposals will be evaluated on the following criteria:
1. Demonstrated experience and expertise in similar projects (80 points)
2. Strength of references (20 points)
Questions regarding this RFP should be direct to: Jules Fishelman, IT Manager, 802-658-6060 x1029

Descriptions of 1st and 2nd Edition of Programming Entity Framework

I’m waiting for the O’Reilly site, Amazon and elsewhere to update the descriptions of the two different editions of my book. Since not everyone is lucky enough to move to VS2010 and EF4, both editions will be on the market. Right now they both have the same description online which is wrong. I don’t want anyone to get the wrong edition and then be misled.

Here are rough drafts of what the updated descriptions will look like:

1st edition (for EFv1 and VS2008/.NET 3.5SP1)

Programming Entity Framework is a thorough introduction to Microsoft’s core framework for modeling and interacting with data in .NET applications. This highly-acclaimed book not only gives experienced developers a hands-on tour of the Entity Framework in Visual Studio 2008 and .NET 3.5, explaining its use in a variety of applications, it also provides a deep understanding of its architecture and APIs. While many of the lessons from this first edition will continue to be valuable as you move to .NET 4.0, the second edition (link???) of Programming Entity Framework targets Visual Studio 2010 and .NET 4.0 where there have been many advancements and additions to the framework. From the Entity Data Model (EDM) and Object Services to EntityClient and the Metadata Workspace, this book covers it all.

 

2nd Edition (for EF4 and VS2010/.NET 4)

Programming Entity Framework, 2nd Edition is a thorough introduction to Microsoft’s core framework for modeling and interacting with data in .NET applications. On the heels of the highly-acclaimed first edition, this book not only gives experienced developers a hands-on tour of the Entity Framework in Visual Studio 2010 and .NET 4.0, explaining its use in a variety of applications, it also provides a deep understanding of its architecture and APIs. You’ll find hundreds of examples and numerous sample applications that take advantage of the new features in Entity Framework 4.0.  Whether you are building Rapid Application Development software or highly architected applications that are testable and provide a separation of concerns,  you’ll find hundreds of examples and numerous sample applications to help you achieve your goals. The book is filled with insight into the inner workings of the Entity Framework to help you become an Entity Framework expert. From the Entity Data Model (EDM) and Object Services, from WPF to ASP.NET MVC, from drag and drop to domain-centric applications, this book covers it all.

Both books are roughly the same length (app 800 page).

The *list* price for both editions is 54.99.

You can pre-order the 2nd edition at OReilly for $39.99 (http://oreilly.com/catalog/9780596807252) and on Amazon for $37.79 (http://learnentityframework.com)

O’Reilly tells me we’re on track for August 15th release. Amazon says August 26th but that’s probably when they expect to have the books in their warehouse to be able to ship.

Code First – It’s not Entity Framework Programming , it’s Just Programming

This is what I’ve realized about using the latest iteration of EF4’s Code First in the EF Feature Pack CTP. (I will keep clarifying that code first and the new EF bits in the CTP are a preview, not for production and subject to change…)

When using code first where you simply create your domain classes and define a DbContext to manage them, Entity Framework quietly slips into the background and does all of it’s work – transforming LINQ queries into store queries, executing them on your behalf, reshaping the query results into your classes, change tracking and then handling persistence to the database.

Between code first’s behind-the-scenes automatic model creation and some of the small but impactful additions to the core API (e.g., DbSet and DbContext), when creating simple applications, you will no longer have to be focused on how to design an Entity Data Model or write Entity Framework code, because most of that will be taken care of you by these new features. Calling context.Customers.Add(myCustomer) doesn’t feel too much different than working with any other collection in .NET. Compare that to context.Customer.AddObject(myCustomer) which your .NET brain fights (just ask Chris Sells :)). Or context.Customers.Remove(myCustomer) which correctly implies that you are removing something from a collection vs. context.Customers.DeleteObject(myCustomer) which is unnatural, but worse, incorrectly suggests that you might be actually deleting this from the database.

While this does feel like an epiphany (oh, it’s just programming) and people like Scott Hanselman are calling code first “the magic EF unicorn”, keep in mind that as you start architecting more complex applications, you’ll still have a lot to understand about the behavior of EF and how to work with it. So, no, I’m not calling “stop the presses” on my book.

Code First will not be for everyone. Many people want and need to build their model by reverse engineering an existing database. Many people like using a modeling tool. That’s why EF has these options and that’s what drove the alignment of the names:

  • Database First
  • Model First
  • Code First

Use what works for you…