Monthly Archives: December 2013

User-Defined Function Overview – Microsoft SQL

User-defined functions (UDFs) were introduced in SQL Server 2000 to provide the coding functionality similar to what is available in general-purpose programming languages. UDFs provide a level of flexibility and reusability that would be impossible to duplicate by using only stored procedures, triggers, and views. These functions, like those in other programming languages, provide reusable code modules that you can invoke with parameters, perform some kind of calculations or actions, and return various
kinds of data.

SQL Server supports three kinds of user-defined functions, each with its own specific features and benefits:

  • Scalar functions are what most developers think of as user-defined functions, because they are most like the functions available in other programming languages and the built-in Transact-SQL (T-SQL) functions. A scalar function can take parameters, contain complex processing, and return a single value of almost any SQL data type.
  • Inline table-valued functions are similar to views in that they each consist of a single SELECT statement and each returns a table object. However, inline table-valued functions can take parameters, whereas views cannot. Like views, you can use inline table-valued functions in statements that update, insert, or delete data, and you can join to them. An inline table-valued function is essentially a view with parameters.
  • Multi-statement table-valued functions are similar to stored procedures, but they return an in-memory table object (a set of rows and columns that you can select from) instead of a static result set. This makes them a powerful view/stored procedure hybrid, because you can perform complex processing in them as in a stored procedure and select data from them as in a view. However, the tables that these functions return are not updatable.

TIP: Another way to categorize the types of functions available in SQL Server is
as scalar and table-valued, based on the type of data returned. With that
categorization, there are then two types of table-valued functions.

UDFs are not allowed to have side effects, which is a bit of a limitation on their use. This means that they are not allowed to make any lasting changes in the database, such as to make changes to data or to alter the schema of any object. But there are more subtle actions that cause changes and therefore are not allowed in UDFs. For example, the RAND function, which generates random numbers, retains state information about the last random number it generated, which changes the state of the function and requires SQL Server to store that state somewhere.

User-defined functions combine some of the best elements of stored procedures and views. Many tasks that you previously performed by using views and stored procedures you can now handle better with UDFs. You can invoke these functions from views, stored procedures, other user-defined functions, batches, and scripts, as well as from external applications.

NOTE:  SQL Server 2000 did not permit nondeterministic functions in the body of a user-defined function. A deterministic function, like LEN, always returns the same result anytime it is called with the same argument values. A nondeterministic function, such as GETDATE(), always returns a different value on each invocation. However, in SQL Server 2005 and later, things have loosened up: GETDATE() is now permissible in UDFs.

Common Language Runtime UDFs

You can create each type of UDF in SQLCLR code as well as Transact-SQL. Transact-SQL is recommended for functions that rely on set-related data manipulation and SQLCLR functions are recommended for functions that require intensive computations or string manipulations, neither of which T-SQL is well suited for. In some cases, the .NET Framework contains base classes that supply functionality that would be difficult to duplicate in Transact-SQL, such as string processing that uses the RegEx class. However, if your functions involve fairly straightforward data manipulation, Transact-SQL is the best choice. This chapter will focus on T-SQL UDFs.

ldn-expertdkielyThis post is an excerpt from the online courseware for our Microsoft SQL Server 2012 Developer course written by expert Don Kiely.

Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor and consultant who travels the country sharing his expertise in SQL Server and security.

Create Child Controls – Microsoft SharePoint 2010

Most web controls that have visual elements compose other controls into a greater whole. Every web control contains a Controls collection property that contains the controls of which it is composed.

The controls in the Controls collection are called child controls because a page is easily visualized as a tree of controls with the page as the root. Each node of the tree can have zero or more children.

Use the CreateChildControls to instantiate any child controls that your web control contains.

The first two things that happen when ASP.NET renders a page are the initialization and loading of each node of the tree. The next thing that happens is the loading of state into each node of the tree so that the tree correctly represents any user input.

State is stored in a hidden form field named __VIEWSTATE and its contents are used to rehydrate a page between postbacks. The loading of ViewState works only if ASP.NET is able to match each node in the current rendering with the previous version—the one with which the user interacted and submitted input.

Consider the following code snippet:

 

If you ran this code in ASP.NET 2.0, perhaps on a WSS 3.0 or MOSS 2007 site, the Web Part would render a button 50 pixels wide without error. However, the event handler will not fire when a user clicks the button because the MyWebPart class creates a new instance of the Button class each time it initializes. The myButton variable then references a new button.

When the ViewState loads to indicate that the user clicked a button, the new button has replaced the original button in the tree and the event doesn’t fire.

Here’s the correct way to write this code:

 

In this example, you are still creating a new instance each time—ASP.NET is stateless after all, but the timing of the operation allows the page rendering infrastructure to correctly associate the button with its state when it adds the button to the Controls collection.

When working with the page rendering life cycle, timing is everything. ASP.NET 3.5, the basis of SharePoint Foundation, is more forgiving in this regard. However, unless you know that your custom Web Part will never run in an older version of ASP.NET, it is a best practice to follow the simple rule—create your child controls inside CreateChildControls.
doug (frame 367 of smile clip)This post is an excerpt from the online courseware for our Microsoft SharePoint 2010 for Developers course written by expert Doug Ware.

Doug Ware is a SharePoint expert and an instructor for many of our SharePoint 2007 and SharePoint 2010 courses. A Microsoft MVP several times over, Doug is the leader of the Atlanta .NET User Group, one of the largest user groups in the Southeast U.S., and is a frequent speaker at code camps and other events. In addition to teaching and writing about SharePoint, Doug stays active as a consultant and has helped numerous organizations implement and customize SharePoint.

What is a Model? – MVC 4.0: Views and Models

The model in the model-view-controller pattern is the representation of the domain in an MVC application. The domain of an application is the problem area the application deals with, usually classes that represent business objects. For example, an online banking application might have a domain that consists of checking accounts, transfers, and bills. An application to manage a pet store’s inventory might have a domain that includes cats, dogs, and pet food. The model of your application consists of the classes that represent this domain.

To be consistent with the principle of separation of concerns, views and controllers should have no knowledge of the business rules in your domain or where the data for your domain is stored—if there is even a persistent storage for the data. Instead, views and controllers interact with the model and other application layers to handle those details.

Most real-world MVC applications will typically make use of some sort of data that is stored somewhere, usually in a relational database such as SQL Server or Oracle, or, at the very least, XML files stored on a server somewhere. No matter what the storage is, the application will contain some kind of data access layer to read and write data. Similarly, all non-trivial applications always have some kind of business rules, ranging from simple requirements that a customer’s last name be provided and that an email address must comply with Internet standards, to rules like all customers who did more than a million dollars’ worth of business with us last year get an automatic 20% discount on all purchases. These business rules may be handled in other layers of the application, but the rules that govern a specific object are present in the model.

Unlike a controller or view, in an ASP.NET MVC application a model is not defined by implementing a specific interface or inheriting from some framework class, or even because the class definition file is in the Models folder in Solution Explorer. Instead, one or more classes are models because of the role they play in the application.

This gives you enormous flexibility in how you implement a model. A model could be a simple class that represents data generated during a single session of the application, destroying the data when a user signs off. It could be a complex set of classes generated by Entity Framework to provide an objectrelational mapping to a relational database with hundreds of tables. Or just about anything in between. You’ll see variations of these options in this chapter. But at its core, a model is just a class that lets the controller interact with your domain and that provides data in that domain to a view.

TIP: A model is domain specific. This means that although you can implement a model just about any way you want, you generally will not want generic ADO.NET objects, such as DataSets, to serve as models. Instead, you’ll normally build a model for a specific application (or set of related applications) that serve specific data and business rule needs.

If a model you build is specific to a single application, you should create the model classes in the Models folder within Solution Explorer. This convention makes it simpler to work with the model classes and makes them easily discoverable when another developer comes along six months from now and tries to figure out what you did. But you can place a model class anywhere within an application. Remember that it is how a model is used that makes it a model, not where it is located or what it implements or inherits from.

If you use a model in several related applications, you can put one or more models in a class library and compile it into a standalone DLL, which you then reference from the applications that use the model.

A best practice in MVC applications is to maintain the separation of concerns between the components of the application. For models, this means that you’ll want to instantiate (or retrieve) the model in the controller’s action methods, using the methods and properties of the model to tell the model what actions to take relative to the data, and then send the data to a view for display to the user.

This chapter explores the use of models in an ASP.NET MVC application, how you can create them, and how you can implement validation rules. You’ll also explore how to interact with models from views and controllers, since none of these components exists in a vacuum. Models, views, and controllers interact in specific ways, so it is impossible to consider models without considering the other components as well.
ldn-pledgerwoodThis post is an excerpt from the online courseware for our MVC 4.0: Views and Models course written by expert Phil Ledgerwood.

Phil Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

The WPF Layout System – Visual C#

Layout in WPF is flow-based, but it also includes automatic resizing and repositioning of controls if the user changes screen resolution or resizes the window containing controls or adds or removes controls at runtime. As you will see in this chapter, this provides resolution and size independent user interfaces.

A window can contain one element, or control. That element will almost always be a container. A container contains controls and, optionally, other containers. All container controls derive from the System.Windows.Controls.Panel class. Layout in WPF is a recursive process. The .NET Framework runtime makes two passes before drawing elements.

In the Measure pass, the runtime queries each element to determine the element’s size and location. In the Arrange pass, the runtime determines the actual size and position for each element. Elements may or may not be sized and located where they requested, depending on the number of elements, the screen resolution, the size of the window, etc.

Layout is not only a recursive process, but it is also an iterative process. The entire layout process occurs each time the user resizes the window or your code adds or removes elements. You should keep this in mind as you design user interfaces.

How does the layout system determine how to size each element? Each element on a window is surrounded by a bounding box, as shown in Figure 1. This represents the space allocated to the element, and therefore represents the maximum size of the element.

helloworld

Figure 1 Each element on a window is surrounded by a bounding box.

The layout system determines the actual size of an element by taking into account the following:

  •  The available screen space.
  • The size of any constraints, such as maximum or minimum height or width.
  •  Layout-specific properties, such as alignment, margins, padding, etc.
  •  The behavior of the parent container.

As needed, the layout system can shrink, grow, or move elements on a window.

Alignment, Margins, and Padding

All elements have four properties that are important to understand, as these play a key role in determining the position of elements in a window. These properties are HorizontalAlignment, VerticalAlignment, Margin, and Padding. Alignment refers to how child elements should be positioned within a parent element’s allocated layout space. The HorizontalAlignment property determines how an element is positioned horizontally within a container. The possible values for this property are Left, Right, Center, and Stretch, as shown in Figure 2. If this property is set to Stretch, which is the default, the control will expand to its maximum available width.

WPFLayoutSystem2

 Figure 2  The HorizontalAlignment property determines how an element is positioned horizontally within a container.

The VerticalAlignment property determines how an element is positioned vertically within a container. The possible values for this property are Top, Bottom, Center, and Stretch, as shown in Figure 3. If this property is set to Stretch, which is the default, the control will expand to its maximum available height.

WPFLayoutSystem3

Figure 3. The VerticalAlignment property determines how an element is
positioned vertically within a container.

The Margin property determines the distance between an element and its child or peers. This property consists of four parts: the left margin, the top margin, the right margin, and the bottom margin. The following XAML sets the margin for an element following this pattern:

<Button Margin=”0,10,0,10″…

The previous code specifies that there should be no additional space on the left and right, but there should be a ten pixel space on the top and bottom. If you want the same margin on all four sides, you only need to specify one value. The following XAML sets the margin to ten on all sides:

<Button Margin=”10″…

The Padding property is similar to the Margin property, however it is only available for certain controls, including Border, Button, and TextBlock. The property adds space between the edge of a control and its content.

Figure 4 shows the use of the Margin and Padding properties, along with horizontal alignment, to control the layout of elements.

WPFLayoutSystem4

Figure 4. You can use the Margin and Padding properties, along with horizontal
alignment, to control the layout of elements.

Containers

As mentioned earlier, each window can contain a single element. This element will typically be a container control. This chapter covers the following containers:

  • StackPanel: Stacks elements horizontally or vertically.
  • WrapPanel: Places elements in rows and columns that wrap as needed.
  • DockPanel: Aligns elements along an edge.
  • Grid: Places elements in rows and columns.
  • Canvas: Places elements according to coordinates.

This post is an excerpt from the online courseware Windows Presentation Foundation Using Visual C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

The Role of the View – ASP.NET

The views in your ASP.NET MVC application are what a user sees. Views are the window into your application, and so is one of the most important parts of the application…along with all the rest of it!

Views provide one of the biggest reasons to use MVC instead of Web Forms. Unlike Web Forms, you have complete control over the HTML that the application generates. There are no server controls as there are in Web Forms that spew HTML, which you have little control over or that are hard to use with CSS and client-side JavaScript.

Having complete control over HTML sounds great in theory, but it could also mean that you’d have to write a lot more HTML by hand. One of the big selling points of Web Forms is that you can do drag and drop development, using server controls that generate massive amounts of HTML based on the properties you set and the data you bind to the controls.

But MVC has a lot of features built in that make the job of writing HTML and other code simpler and more manageable, while letting you retain control over most of the generated HTML. And when you need complete control, you can bypass the MVC features and write all the beautiful HTML you care to write.

The trick to writing good views in MVC is to keep the view focused on the user interface only. This means that there should be no code that directly reads or writes to a data store, no business rule implementations, nothing that isn’t directly related to interacting with the user. The ideal view should consist of a lot of HTML, maybe some client-side JavaScript (perhaps including Ajax), and a little code that reads data from the model or ViewData for the purpose of displaying data to the user. It might be appropriate to put some logic in a view, but it should only be presentation logic needed to dynamically interact with the
user. Anything else you should rip out and put in the controller or model. Make that your solemn goal.

The purest way to think about views is that the controller hands a model to the view, and the view converts it into something that is presented to the user. We’ve found this way of thinking to be a helpful context for understanding what views do and how to create them, as well as where to implement different kinds of logic.

In this chapter, you’ll learn about how views work, how you can add dynamic data to the view, how you can bundle and minify files, a little bit about the view engine that makes it all work, and ways to adhere to MVC’s DRY— Don’t Repeat Yourself—principle by creating reusable controls that you can use in multiple views.

Figure below shows a graphic view of the interactions of the components of an MVC application. In order to handle a user request, the controller interacts with the model in whatever way is necessary to respond to the request. The controller then selects a view and passes it whatever data the view requires to generate a page. The view engine then reads the view template and dynamically generates the HTML that is sent to the user.

theroleofview1

In this chapter, you’ll learn some of the many features you can use to build views that provide a robust user interface for your applications. The MVC framework has a rich infrastructure for creating responsive and attractive web sites for your users.
ldn-pledgerwoodThis post is an excerpt from the online courseware for our Introduction to ASP.NET MVC 4.0 course written by expert Phil Ledgerwood.

Phil Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

Lists and Libraries in the Object Model – Microsoft SharePoint 2010

The functionality that features provide to define and create lists is useful, but the static nature of XML means that you need more tools at your disposal to fully exploit the power of lists and libraries. Fortunately, just as you’d expect, the core SharePoint assembly contains a robust set of classes to allow automation of lists and their contents.

As you explore these classes, you may find yourself in familiar territory: The names may be new, but the techniques closely resemble those that you use to manipulate any .NET collection. The techniques for adding, editing, and deleting list items resemble those for every data access stack from Microsoft since Windows development first became popular in the 1990s.

In fact, the only unusual aspect of working with SharePoint lists and libraries is the query syntax which you will see in a later section.

You can accomplish a great deal in code with a relatively small number of
classes:

  • SPListCollection
  • SPList
  • SPDocumentLibrary
  • SPListItemCollection
  • SPListItem
  • SPListView
  • SPContentType
  • SPField

Each SPWeb instance exposes an SPListCollection via the Lists property that contains all of the SPList instances in the web. Some of the SPList instances are document libraries and are actually of type SPDocumentLibrary. Each SPList and SPDocumentLibrary exposes its items via the Items property, which is of type SPListItemCollection. Each item is an SPListItem.

The other classes, SPListView, SPContentType, and SPField represent a list’s presentation and structure.

Retrieving List Instances

If you need to access a list within a page context, perhaps as part of a custom list form, you can get the current List or ListId from SPContext.Current. In other situations, feature event receivers for instance, you access a list instance via the containing web.

Lists and libraries are members of a specific web. Therefore, instances of the SPWeb class expose a property named Lists that returns an instance of SPListCollection that you can use to enumerate all of the lists in the web.

The SPListCollection Item property has three overloads that you can use to retrieve a specific list instance. One takes the list’s GUID, one takes the list’s name, and the other takes the list’s ordinal position in the collection.

Alternatively, you can use the SPWeb.GetList method to retrieve a list based on its URL. This method is especially versatile because the URL can point directly to the list or to any of its forms using an absolute or site relative format.

doug (frame 367 of smile clip)This post is an excerpt from the online courseware for our Microsoft SharePoint 2010 for Developers course written by expert Doug Ware.

Doug Ware is a SharePoint expert and an instructor for many of our SharePoint 2007 and SharePoint 2010 courses. A Microsoft MVP several times over, Doug is the leader of the Atlanta .NET User Group, one of the largest user groups in the Southeast U.S., and is a frequent speaker at code camps and other events. In addition to teaching and writing about SharePoint, Doug stays active as a consultant and has helped numerous organizations implement and customize SharePoint.

Introducing Windows Presentation Foundation – C# 2010

Modern applications require a modern user interface. On the other hand, applications you create using Windows Forms, the standard user interface design package that Visual Studio has provided for past versions, look little different than applications written using tools you might have used in 1995.

No matter how you dress them up, forms created using the Windows Forms package generally look pretty much the same, as shown in Figure 1. Although you can create other types of applications, using Windows Forms, you’re on your own—the tools exist to create more creative forms, but you must write all the code for each application. You can create non-rectangular forms; you can create forms that scale. But you’ll write a lot of code to make it happen.

WPF1
Figure 1. It’s an attractive form, but it looks like every other form.

Although Windows Forms provide a rich set of tools for creating business applications, the package leaves a great deal to be desired for building intricate, rich, modern graphically oriented applications.

What if you want to create an application that uses a completely new type of interface? Perhaps you don’t want rectangular controls, but rather, would like to use your own styles?

One thing is for sure: If you’ve ever seen anyone use a computer interface in a movie or television show, you can be assured that you weren’t seeing an application created using Windows Forms. As you know, creating a visually appealing application using Windows Forms can be challenging. To be honest, up until recently, computer graphics hardware really wasn’t powerful enough for a forms package richer than Windows Forms. You can certainly use Windows Forms to create interfaces as you might see in a movie, but it’s not easy, and each application you write would require its own set of tools.

In addition, using Windows Forms, three-dimensional graphics were extremely difficult without using external libraries. Even then, your code was at the mercy of hardware that might not provide the power necessary to perform the required mathematical calculations. In addition, the underlying graphics engine, built into Windows for many years, is extremely limited.

Windows Presentation Foundation (WPF) provides a new design medium. WPF has been created from the ground up to take advantage of hardware power, and provides a consistent, powerful graphics platform. WPF includes an integrated, vector-based (as opposed to pixel-based) composition engine, which utilizes the power of the computer throughout the graphics stack. In other words, it takes advantage of both the processing power of the computer, and of the GPU (Graphics Processing Unit) built into the graphics hardware. WPF provides full support for resolution independence—as you move from one screen resolution to another, your WPF applications scale appropriately.

WPF introduces a unified approach to user interface, documents, and media: it provides full support for mixing all types of user interaction in a single application. Retrieve input from a user, display a movie, render the contents of a newspaper, all within a WPF application using native controls and rendering support.

From a programmer’s perspective, WPF makes rich document integration part of the development experience. Unlike Windows Forms, where you can bolt on media support, this support is simply part of WPF. In addition, WPF fully supports separation of design and code, allowing you to bring designers directly into the development process. Because you can use declarative coding to create your WPF applications, designers can create the user interface with either Visual Studio or other WPF-enabled tools (such as Microsoft’s Expressions products), and then you, as a developer, can add the programmatic functionality later. Finally, deployment of WPF applications is easy; it allows administrators to deploy and manage applications securely.

This post is an excerpt from the online courseware Developing Applications with Entity Framework 4.1 Using C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

Choosing the Right Action – Microsoft SQL Server 2012

The job of the action invoker to select the appropriate action method is more complicated than may appear on the surface. There could be multiple overloaded methods with the same name in a controller, they may be decorated with different attributes that make their selection appropriate in some scenarios and not others, their action method name may be different from their class method name, and other complications. Designing an effective controller requires that you understand how the selection process works.

The first thing that the action invoker does is to look for the action portion of the route definition for the request. Using the default route defined in a new MVC application shown below, it is the name at the second position.

 

Even if the current URL doesn’t include the action portion of the route, the default route definition defines it to be the “Index” action.

Once the action invoker has the name of the action, it needs to map that action name to a method of the controller. The simplest case occurs when there is a single method in the controller class with a name that matches the action name. For example, in a new MVC application the Index action of the Home controller maps to the single Index method in that controller.

But what qualifies as an action method? Is every method defined in the controller a potential action method? Not at all. There are a few requirements that a method must meet for the action invoker to consider it to be an action method candidate:

  •  It must be a public method and not marked as static.
  •  It cannot be a method defined on System.Object or the Controller base class. In other words, it must be defined within your custom controller object, not inherited from another object. So ToString could not be an action method because it is defined on System.Object.
  •  It cannot be a special method, such as a constructor, property accessor, or event accessor.
  •  It cannot have the NonActionAttribute decoration. This attribute is handy if you want to include a public method in a controller but don’t want to use it as an action method.

Taking all these restrictions into consideration, the action invoker uses reflection to find all methods in the controller with the same action name as the action name specified in the URL and meet the previous requirements.

But here is where things get a bit murky. Through the use of attributes on the controller’s methods, there could be multiple methods with the same name, the action name could be different from the method name, and there may be a selector attribute that restricts which requests an action method can respond to. This can create a bit of a gauntlet that the action invoker must navigate in order to find the correct action method, so let’s explore these action method features.

WARNING! By default, anyone anywhere could invoke any public method you create in a controller, unless you decorate the method with the NonAction attribute. This sounds scary, but most of the time the only public methods you have in a controller class will be action methods, so this is a non-issue.

ldn-expertdkielyThis post is an excerpt from the online courseware for our Microsoft SQL Server 2012 Developer course written by expert Don Kiely. 

Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor and consultant who travels the country sharing his expertise in SQL Server and security.

Domain Centric Modeling – Microsoft SQL Server 2012

When the first version of Entity Framework came out, it included support for database-first design, which would reverse engineer an existing database and build a model for you. You could build a model using the designer, but there was no tooling support for building a database from the model, so you had to perform that work yourself. The next version of Entity Framework, version 4, released with .NET 4 and Visual Studio 2010, added the necessary tooling support that made model-first design a viable option for using Entity Framework. Through these two releases, the database and model were the focus of early development work on a project. But if you follow domaincentered design, you probably found that Entity Framework really didn’t fit into the way you create applications.

All that changed with Version 4.1 of Entity Framework, released in the early part of 2011. This version added yet another option, code-first design. Codefirst design lets you create the domain model for your application by building Plain Old CLR Objects (POCOs), with no Entity Framework code whatsoever and without using any base classes. Then, through some clever features, you can create a context class that almost magically turns the objects into fully functional entity data objects. Even more amazingly, you don’t have to worry about creating the database at all. Assuming that you can live with the default conventions that you’ll learn about in this chapter, Entity Framework will create the database for you automatically when you first run the application.

The way that code-first works by default will probably work for most applications early in their development cycle. But when you’re ready to deploy the application to a production server, or need more flexibility in how Entity Framework creates a database, you can take advantage of data annotations on the model classes or use a fluent API to take control of the process. And even if you have an existing database that the application will use, you can still use code-first design and map the POCOs to the existing tables and fields.

The biggest benefit of code-first design is that it lets you focus on domaincentric modeling for application development, focusing on the data objects in your application rather than on the database or the Entity Data Model. In fact, your application won’t even have a model, and won’t have an .edmx file in the project, or any XML mapping code. Entity Framework takes care of inferring the model—including the conceptual, storage, and mapping models—at runtime. It really is a code-centric style of writing database applications.

Code-first design works so well and is implemented so nicely that we are confident that it will become the method of choice for new application development.

NOTE Code-first design is only available with Entity Framework 4.1 and later. This is an out-of-band release made available well after the release of Visual Studio 2010, .NET Framework 4, and Entity Framework 4. As a result you’ll need to download and install this release separately. See the course introduction for information.

Using Code-First

There are two different ways you can use code-first for development. The first, and what we expect will turn out to be the most common way, is to write data model .NET classes in your application first, then let code-first in Entity Framework create the database for you. This is the usage scenario that you will learn about in this chapter. Using code-first this way is the easiest, most agile way to jump-start database development, and lets you evolve and refactor the application in its early stages right through to production. Code-first can even update the database as you make changes to the model.

The other usage scenario is to again create the data model classes in your application, then map those data classes to an existing database. This will provide the information Entity Framework needs to provide data access between the application and the database, without the formality of an Entity Data Model. This might sound a little like database-first design, but the difference is that you create your own POCOs rather than having Entity Framework generate them from the Entity Data Model.

As you’ll learn later in the chapter, there are two ways in Entity Framework to map classes to objects in a database, no matter which usage scenario you use. One uses data annotations on the classes and properties of the data model classes, and the other uses the DbModelBuilder API to control the mapping in code.

ldn-expertdkielyThis post is an excerpt from the online courseware for our Microsoft SQL Server 2012 Developer course written by expert Don Kiely. 

Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor and consultant who travels the country sharing his expertise in SQL Server and security.