|
|
YOUR FEEDBACK
|
TOP MICROSOFT .NET LINKS .NET News Desk
Taking Advantage of the Partial Class with the ADO.NET Entity Framework
So you're building a data-driven application and you've got an ADO.NET Entity Model abstraction around your database
By: Kevin Hoffman
Mar. 29, 2008 05:30 AM
Digg This!
So you're building your data-driven application and you've got an ADO.NET Entity Model that represents an abstraction around your database. Maybe you're even pretty savvy and you've used inheritance and some filters to enhance the entity model so that it really is an entity model and not just a raw translation of your database schema into objects. One thing that I have noticed is that in a lot of sample code, a lot of utility functions end up being put in inefficient locations because people forget that the entity model is a partial class. This means that you can extend the model with your own properties and methods. For example, what if you want to implement a keyword search throughout your entity model and you know that you will probably have multiple entry points in your application utilize that search function. You could probably create a class called EntityTools or some such and create a method called Search(string keyWord) , but there's a better place to put that - right in the model! Take a look at this method: public List<Customer> Search(string keyWord) So.. now you can write code that consumes your model like this: using (CustomerEntities ci = new CustomerEntities()) Not only is this easier to follow and easier to read, but its easy to maintain and you can re-use those same methods for any entity model that happens to have the same or similar schema. You can also define custom properties that expose data in a specific way that you know you will be querying frequently: public IQueryable<Customer> PastDueCustomers This code automatically creates a queryable property of customers that have unpaid balances remaining in their line item lists. Can you imagine having to do subqueries of Past Due Customers, for example, sorting the list of past due customers by their past due amount and then sub-filtering that list by those customers who are not on the 'Premier' advantage plan yadda yadda. You can use PastDueCustomers as a query source, like this: var reallyComplicatedQuery = So, the next time you go to add additional business logic to your model or you need some utility methods, consider putting them in a partial class that is the same name as your model in the same namespace as your model and you may just find that your ADO.NET EF experience got a little more pleasant.
MICROSOFT .NET LATEST STORIES
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
|
SYS-CON FEATURED WHITEPAPERS MOST READ THIS WEEK BREAKING NEWS FROM THE WIRES
|
|||||||||||||||||||||||||||||||||||