Is this .Net Type Assignable from another Type?
I have run into this a few times and always have to go to the MSDN to find the answer. I have a situation where I needed to determine if a given type can be treated as a base type in an object factory. I wanted to be able to create my concrete classes without having to do a switch statement for each type.
First I had to determine if the types were assignable to each other, then find the type to implement. I will cover that in another article. In this one I just want to cover the assignment test.
Can this type be assigned?There is a function IsAssignableFrom that you can call on a System.Type.
if( ParentType is ChildType )
It actually has to be written the other way around.
if( ChildType.IsAssignableFrom(ParentType) )
Quick Extension Method
So instead of having to do that all over my code, I wrote an extension method to allow me to do it following a different ordering. I actually got this basic idea from one of the comments on the MSDN page.
if( parentType.CanBeTreatedAsType(childType) )
As you can see the extension method lets you write the syntax in a more natural manner. Your preference may differ, but this makes more sense to me.
Example Codepublic static class DataExtensionMethods
{
public static bool CanBeTreatedAsType(this Type CurrentType, Type TypeToCompareWith)
{
if (CurrentType == null || TypeToCompareWith == null)
return false;
return TypeToCompareWith.IsAssignableFrom(CurrentType);
}
}
void Main()
{
System.Type parentType = typeof(ParentClass);
System.Type childType = typeof(ChildClass);
bool ChildToParent = childType.CanBeTreatedAsType(parentType);
Console.WriteLine("Child can be treated as parent: " + ChildToParent );
bool ParentAsChild = parentType.CanBeTreatedAsType(childType);
Console.WriteLine("Parent can be treated as child: " + ParentAsChild );
}
public class ParentClass
{
public ParentClass()
{
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base()
{
}
}
Guest Blog Post: How to Jumpstart Your Career as a DBA by Thomas LaRock
You are a SQL Server DBA, and I know what you are going through.
You are frustrated at having to correct other people's work. You are tired from being woken at odd hours, or needed to work on weekends.
And the better you get at your job, the more likely you cannot advance in your career because they need to keep you and your skills right there in that cube. You feel stuck.
We've all felt that way. And I'm here to tell you the three things you can do RIGHT NOW that will help you give your database career the jump start you've needed. Separately each one will help to provide you a boost in some way. When done in unison the benefits (both immediate and long-term) will result in an amazing transformation for your career.
So what are you waiting for? Get started by...
1. Downloading SQL2012
Have you ever been with a senior administrator and thought "wow, they sure know a lot of stuff"? Well I am here to tell you that they weren't born with all that knowledge. No, they acquired it over time. And often they learned it while it was still new. Guess what? You have that exact same chance right now! With SQL2012 comes new features such as AlwaysOn and Columnstore indexes. You can learn all about features such as these and in three years people will look to you as the expert. Trust me.
2. Joining PASS
The Professional Association for SQL Server is a group of individuals who are dedicated to the use and care of SQL Server as well as each other. PASS members are always looking to connect, learn, and share with one another information about current in-depth Microsoft SQL Server content. Through knowledge sharing and peer-based learning PASS members find themselves growing their careers by leaps and bounds as database professionals.
Joining PASS is free. and chances are you can find a local PASS chapter or SQL Server user group close to where you live or work right now. Before I joined PASS I used to think that the day-to-day struggles I faced were unique due to the fact that I was working alone. After joining PASS and connecting with other individuals I found out that I wasn't alone, and I found lots of great resources to help me be more effective in my role as a DBA.
3. Joining Twitter
If you have not yet joined Twitter, there is still time. if you don't believe in the value of joining Twitter then try an experiment. Register and set up a Twitter account and post a question during a weekday afternoon. You only get 140 characters, so you'll need to be brief, and (this is most important) use the following 'hashtag' at the end of your tweet: #sqlhelp. When you do you will find dozens of people available to help answer your question, in real-time. And often these folks are the top tier of SQL pros out there, such as Paul Randal (blog | @PaulRandal) or Jonathan Kehayias (blog | @SQLPoolboy).
Beyond the use of Twitter to answer questions you will find a community of folks that are just there for each other. Think of it as a virtual watercooler where you can go for a quick conversation on whatever topic of choice you want or need. For folks who work alone (from their homes) or for database professionals that work on small teams (or just by themselves in a cube somewhere) the ability to reach out and share your experiences with others makes your world a little less lonely.
What are you doing here, still reading this blog post? The sooner you get started the sooner you can reap the benefits.
Thomas LaRock
Vice President of Marketing
Professional Association for SQL Server
Blog: http://thomaslarock.com/
Twitter: @SQLRockstar
Guest Blog Post: How to Jumpstart Your Career as a DBA by Thomas LaRock
You are a SQL Server DBA, and I know what you are going through.
You are frustrated at having to correct other people's work. You are tired from being woken at odd hours, or needed to work on weekends.
And the better you get at your job, the more likely you cannot advance in your career because they need to keep you and your skills right there in that cube. You feel stuck.
We've all felt that way. And I'm here to tell you the three things you can do RIGHT NOW that will help you give your database career the jump start you've needed. Separately each one will help to provide you a boost in some way. When done in unison the benefits (both immediate and long-term) will result in an amazing transformation for your career.
So what are you waiting for? Get started by...
1. Downloading SQL2012
Have you ever been with a senior administrator and thought "wow, they sure know a lot of stuff"? Well I am here to tell you that they weren't born with all that knowledge. No, they acquired it over time. And often they learned it while it was still new. Guess what? You have that exact same chance right now! With SQL2012 comes new features such as AlwaysOn and Columnstore indexes. You can learn all about features such as these and in three years people will look to you as the expert. Trust me.
2. Joining PASS
The Professional Association for SQL Server is a group of individuals who are dedicated to the use and care of SQL Server as well as each other. PASS members are always looking to connect, learn, and share with one another information about current in-depth Microsoft SQL Server content. Through knowledge sharing and peer-based learning PASS members find themselves growing their careers by leaps and bounds as database professionals.
Joining PASS is free. and chances are you can find a local PASS chapter or SQL Server user group close to where you live or work right now. Before I joined PASS I used to think that the day-to-day struggles I faced were unique due to the fact that I was working alone. After joining PASS and connecting with other individuals I found out that I wasn't alone, and I found lots of great resources to help me be more effective in my role as a DBA.
3. Joining Twitter
If you have not yet joined Twitter, there is still time. if you don't believe in the value of joining Twitter then try an experiment. Register and set up a Twitter account and post a question during a weekday afternoon. You only get 140 characters, so you'll need to be brief, and (this is most important) use the following 'hashtag' at the end of your tweet: #sqlhelp. When you do you will find dozens of people available to help answer your question, in real-time. And often these folks are the top tier of SQL pros out there, such as Paul Randal (blog | @PaulRandal) or Jonathan Kehayias (blog | @SQLPoolboy).
Beyond the use of Twitter to answer questions you will find a community of folks that are just there for each other. Think of it as a virtual watercooler where you can go for a quick conversation on whatever topic of choice you want or need. For folks who work alone (from their homes) or for database professionals that work on small teams (or just by themselves in a cube somewhere) the ability to reach out and share your experiences with others makes your world a little less lonely.
What are you doing here, still reading this blog post? The sooner you get started the sooner you can reap the benefits.
Thomas LaRock
Vice President of Marketing
Professional Association for SQL Server
Blog: http://thomaslarock.com/
Twitter: @SQLRockstar
CodeSmith Generator 6.0-Intellisense Improvements
KB2650605 QFE : VS2010 sp1 VB web form editor may not become editable during debugging
We recently released a VS2010 sp1 QFE KB2650605 to solve a VB editor debugging problem. During VB web form debugging, VB web form may become un-editable if there are server tags inside. If you develop and debug VB web forms, you might be interested to download this QFE.
http://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=40811
Best regards,
Xinyang Qiu
Web Platforms and Tools Team
Debugger Canvas 1.1 Released
Since the initial release of the Debugger Canvas last summer, the team has been busy taking all the great feedback from you, acting on it, and preparing a new release. That release, Debugger Canvas 1.1, has just been released on DevLabs!
The teams has focused on fixing numerous bugs as well as addressing a number of performance issues, but has also poured a number of new features into this release:
- Easily turn Debugger Canvas on or off, even in the middle of a debug session
- Quickly navigate up and down the call stack in the canvas using the keyboard or the mouse
- See Multiple threads together on the canvas, each thread identified by its color.
- See recursive calls side by side
- Edit code directly in the code bubbles ( this is now on by default ).
Please take this new release out for a test drive by going over to DevLabs and downloading this new version. And as always, the team welcomes and looks forward to your feedback. Please visit the DevLabs forum and let us hear about it!
Cheers!
Cameron
Microsoft SQL Server Migration Assistant 5.2 is Now Available
SQL Server Migration Assistant (SSMA) v5.2 is now available. SSMA simplifies database migration process from Oracle/Sybase/MySQL and Microsoft Access to SQL Server and SQL Azure. SSMA automates all aspects of migration including migration assessment analysis, schema and SQL statement conversion, data migration as well as migration testing to reduce cost and reduce risk of your database migration project.
- The new version of SSMA - SSMA 5.2 provides the following major enhancements:
- Support conversion of Oracle %ROWTYPE parameters with NULL default
- Support conversion of Sybaseâs Rollback Trigger
- Better user credential security to support Microsoft Access Linked Tables
Reduce Cost and Risk of Competitive Database Migration
Does your customer have Oracle, Sybase, MySQL or Access databases that you like to migrate to SQL Server or SQL Azure? SQL Server Migration Assistant (SSMA) automates all aspects of migration including migration assessment analysis, schema and SQL statement conversion, data migration as well as migration testing. The tool provides the following functionalities:
- Database Migration Analyzer: Assess and report complexity of the source database for migration to SQL Server. The generated report include detailed information on the database schema, percentage of the schema objects that can be converted by the tool, and hours estimate for manually migrating those schema objects that cannot be converted automatically. The information can be used for your to decide and to plan for migration. Visit SSMA team site for video demonstration of this feature.
- Schema Converter: Automate conversion of schema objects (including programming code inside package, procedure, function) into equivalent SQL Server objects and T-SQL dialect. The tool provides ability to customize the conversion from hundreds of project setting options according to your specific business requirements. A report will be generated at the end of conversion for any object statement not supported for automated conversion. You can drill down to each of the migration issues and obtain side-by-side comparison between the original source code and the converted source code as well as make necessary modification directly from SSMA user interface. Visit SSMA team site for video demonstration of this feature.
- Data Migrator: Migrate data from the source database to the SQL Server using the same conversion logic and type mapping specified in the project setting during schema conversion. Visit SSMA team site for video demonstration of this feature.
- Migration Tester: Facilitate unit testing of converted program in SQL Server.
Simplify Migration to SQL Azure
Customers can simplify their move to the cloud with the SSMA. You can migrate from competitive database directly to SQL Azure. The tool reports possible migration issue to SQL Azure, convert schema, and migrate data to SQL Azure database. SSMA supports SQL Azure migration from Microsoft Access, MySQL, and Sybase.
Receive FREE technical support and migration resources.
Microsoft Customer Service and Support (CSS) provides free email technical support for SSMA. SSMA product web site and SSMA team blog site provides many resources to help customer to reduce cost and risk for database migration.
Download SQL Server Migration Assistant (SSMA) v.5.2
Launch the download of the SSMA for Oracle.
Launch the download of the SSMA for Sybase.
Launch the download of the SSMA for MySQL.
Launch the download of the SSMA for Access.
Join us March 7, 2012 for the Virtual Launch of SQL Server 2012!
On March 7, 2012 we are hosting the SQL Server 2012 Virtual Launch Event (VLE), to share the latest on SQL Server 2012 and the evolution of the Microsoft data platform. Through our VLE, anyone, anywhere in the world can simply log in and be a part of this amazing experience â consuming content at your own pace while still experiencing all the benefits of a tradeshow event.
What are some great reasons to check out our VLE experience?
You want to learn from SQL Server insiders
Learn more about the new features of SQL Server 2012 through access to more than 30 sessions. Our experts will demonstrate how your business can go further, forward, faster by capitalizing on mission critical capabilities, new features that drive true business insights and the most cloud-ready SQL Server ever.
You want to engage with Partners and Customers
Visit our Partner Pavilion to discuss how partner and pioneer customer solutions integrate with SQL Server 2012.
You want to chat live with product experts and MVPs
Chat live with product experts and MVPs to get the inside scoop. Our team will be on hand to answer questions about SQL Server 2012 and network in the virtual lounge.
You want to engage with the community â and maybe win a prize!
Participate in virtual launch activities like the keynote speech, technical demos and networking lounge, and collect points to earn cool prizes such as cash gift cards, SQL Server Gear, and Xbox systems. The more points you earn, the bigger your prize could be!
Register today at: www.sqlserverlaunch.com
The Co-operative Group saves millions by switching from Oracle to SQL Server
We talk a lot about the features and technical âhow toâ behind SQL Server, but our favorite topic is showing real-world examples of how it helps our customers achieve their goals and save millions of dollars. One great example of this is The Co-operative Group and their switch from Oracle to SQL Server.
The Co-operative Group operates 5,000 retail stores, and is one of the worldâs largest member-owned businesses. The Groupâs top strategic priority is expanding its membership base, and they set an aggressive goal to grow to 20 million members by 2020.
But instead of helping the Group achieve its goals, technology and licensing models were a barrier to success. The Groupâs previous membership system was an Oracle solution, hosted by a provider that charged per member â a situation where scaling membership would have cost the company tens of millions of dollars. âIt would have been financial suicide if we had tried to use the existing solution to accomplish our growth goals,â said Chris Sproston, the head of software development at The Co-operative Group.
To realize the companyâs goals, The Co-operative Group turned to SQL Server 2008 R2 and a variety of other Microsoft products and services. Working with Microsoft partner HCL Infosystems, they developed a solution that stores account information, records transactional data and supports web-based self-service account management.
Using this new solution, The Co-operative Group improved member services with enterprise-wide reporting and analysis tools, and increased the security of customer information with highly specific access privileges and transparent data encryption. As a result, the companyâs IT department can now spend time innovating and adding features, instead of using its resources to manage new reports or queries.
âBecause SQL Server 2008 R2 is so scalable, we can expand from 6 million to 20 million members for 10 percent of what it would have cost on our old solution,â said Chris Sproston, head of software development for The Co-operative Group.
By implementing the Microsoft system, The Co-operative Group will be able to reduce the cost of its long-term growth goal by tens of millions of dollars. And thatâs the kind of success story we love to be able to share.
For more information about The Co-operative Groupâs solution and how they plan to save millions by switching from Oracle to SQL Server, check out the case study.
Customers using SQL Server 2012 today!
In my last post in November on Mission Critical customer implementations of SQL Server, I mentioned that we would include some details on customers already using SQL Server 2012. Over the last few weeks, we have released some of these first stories highlighting customers that are already realizing the benefits of using new features such as AlwaysOn, Power View and Data Quality Services. This is an opportunity to bring some of those first stories into one place so you can get an overview of these stories. Below you will find a short description of the case studies with links to more detailed accounts of the stories.
Mediterranean Shipping Company
âSQL Server 2012 AlwaysOn gives us an integrated high-availability and disaster recovery solution that delivers around-the-clock data access and fast performance for less moneyâ
- Fabio Catassi, Chief Technology Officer
As the second-largest shipper in the world, Mediterranean Shipping Company (MSC) must access and share operational data with global employees and partners all day, every day to deliver excellent service. In 2011, the company began to update core systems with new software from Microsoft to implement innovative availability and disaster recovery capabilities. As a result, MSC can facilitate growth by speeding data access, minimizing downtime, improving security, and reducing costs.
Great Western Bank
âBanks that try to compete against us are simply going to be at a disadvantage if they donât have the enterprise-ready data-warehousing and BI capabilities that SQL Server 2012 and Power View give us."
- Ron Van Zanten, VP of Data Quality
To support ambitious growth plans, Great Western Bank needed to increase profitability, simplify compliance, and gain better insight into customer relationships. The bank deployed a Microsoft data warehouse and business intelligence solution because of previous success in building an extremely complex system with the technology. The bank can now more easily attract and retain customers, maximize the amount of money it loans and invests, and prove its growth capacity to regulators.
RealtyTrac
âWith SQL Server 2012 Data Quality Services, we will help our customers clearly see all lenders involves in a foreclosure. This will help our customers make better, more informed buying and selling decisions.â
- Richard Sawicky, Senior Director of Database Technology
To help its customers make real estate decisions, RealtyTrac needed to provide more accurate property data and a clearer view of each propertyâs mortgage information. The company deployed a Microsoft solution to take advantage of tools that information workers can use to improve data quality and analysis. With accurate and comprehensive data, RealtyTrac can help its customers make better decisions and improve its own competitive advantage. It also expects to save IT time and costs.
ServiceU
âThe SQL Server 2012 online indexing capabilities alone save us up to 20 minutes a year in downtime, or 38.5percent of allowable downtime. That might not sound like much, but it is huge for us and our customers.â
- David Smith, Director, Software Architecture
ServiceU, part of the Active Network, Inc. (NYSE: ACTV), needed to increase availability for its mission-critical online event management applications. The company implemented a new Microsoft high-availability and disaster recovery solution, which reduces downtime and gives customers more confidence in the availability of the applications. Also, the company has cut failover time between nodes by half, made IT administration simpler, and expects to reduce development costs.
EdgeNet
âNow, with SQL Server 2012, we can run any data export our customers want whenever they want it, so weâre better able to meet their needs and support new customers.â
- Michael Steineke, Vice President of IT
To improve customer service and support growth, Edgenet needed to export critical product data more efficiently to online retailers and search engines that provide the data to shoppers. It also wanted to increase employee and customer insight into this data. Edgenet deployed a Microsoft solution for enterprise-level performance, availability, and business intelligence. Edgenet can now serve more customers faster; its network is simpler; and it is improving its competitive advantage.
Are there many other SQL Server 2012 stories coming?
Expect to see a lot more SQL Server 2012 case studies (and earlier versions of SQL Server) published over the next few months. To make it easier to find these stories, we will be adding a new Customer Stories section to the SQL Server website in the next few weeks, so you can easily find stories that match the Version, Workload, Industry or Country of implementation you are looking for.
David Hobbs-Mallyon
Senior Marketing Manager
SQL Server Marketing
New and Improved Generator Overview Video
Displaying DSC information with a Standard Horizon Chartplotter
As I indicated in an earlier post my goal is to display DCS information on my CP170 chartplotter.
Well I got it working this weekend and since I couldnât find much information about this on the web thought I would post what it looks like and how does it work.
- Have a friend or back up radio send a position report or request to an NMSI # of the radio you have your Chartplotter connected with
- Receive that message on the radio connected to the chart plotter (see image)

- Automatically your Chartplotter should display the request and ask if you want to see on chart

- Displaying the request gives you three options: goto vessel, go back your previous screen and or view the screen the hailing vessel is at

- The CP170 also creates a Waypoint with the name of the Vessel in the NMSI directory (hard to see as there are couple of on top of each other)

- During this whole time I am also viewing ships on the NX40 using AIS (Still bummed I can not display DSC information on the Simrad!) Notice the different type of ships appear in different colors!
7. Selecting one of the ships I see information about itâŠ..
How to wire your DSC VHF to a NMEA 0183 Chartplotter so you can remove them
All the Chartplotters I have seen have water tight disconnects making them very easily removed â like my Simrad NX40(See picture)

BUT all the NMEA 0183 DSC VHF radios I have seen have these same connections hardwiredâŠ.
So if you wire your VHF to your Chartplotter through the dashboard or binnacle your VHF is stuck in your boat âand easy pickings for any thieves. (Definitely not where I want my Standard Horizon Matrix 2150 to end up!)
Really wanting to remove my electronics while left the boat moored I started looking at my options for quick disconnect plugs (like what NMEA 2000 gives you). I am sure there are some really good quick disconnect plugs out there â but not at my local RadioShack!
What they did have was gold plated 3.5mm headphone extension cables for ~$8/pair. So I bought a couple of these (plus some I had laying around) and cut them in half soldering/heat shrinking each half to the VHF and the Chartplotter.
From the Chartplotter view this plug now has the following signals running through it:
The actual chartplotter wire belowâŠthe red tape is to distinguish this cable from the power cable (Same exact cable just plugs into different ports on the chart plotter)
Below is the other half of the wires on my Matrix 2150.
The reason there are three:
- The red shrink wrapped female â DSC to my Standard Horizon CP170 ( you can see the CP170 mount in the background below)
- Black Female â AIS to my NX40
- Black Male â to my PA/Fog Horn on the roof
Now all my electronics can come out of the boat while I am not in it!
Chuck
EF 4.3 Beta 1 Released
At the end of November we released Beta 1 of Code First Migrations. At the time we released Code First Migration Beta 1 we also announced that we would be rolling the migrations work into the main EntityFramework NuGet package and releasing it as EF 4.3.
Today we are making Beta 1 of EF 4.3 available. This release also includes a number of bug fixes for the DbContext API and Code First.
We are planning for this to be the last pre-release version of migrations and our next release will be the final RTM of EF 4.3.
What Changed
This release has been primarily about integrating migrations into the EntityFramework NuGet package, improving quality and cleaning up the API surface ready to RTM.
Notable changes to Code First Migrations include:
- New Enable-Migrations command. You now use the Enable-Migrations command to add the Migrations folder and Configuration class to your project. This command will also automatically fill in your context type in the Configuration class (provided you have a single context defined in your project).
- Update-Database.exe command line tool. In addition to the power shell commands this release also includes Update-Database.exe which can be used to run the migrations process from a command line. You can find this tool in the âpackages\EntityFramework.4.3.0-beta1\tools\â under your solutions directory. The syntax for this command line tool is very similar to the Update-Database power shell command. Run âUpdate-Database /?â from a command prompt for more information on the syntax.
- Migrations database initializer. This release includes the System.Data.Entity.MigrateDatabaseToLatestVersion database initializer that can be used to automatically upgrade to the latest version when your application launches.
- Complete xml documentation. This release now includes xml documentation (IntelliSense) for the migrations API surface.
- Improved logging. If you specify the âVerbose flag when running commands in Package Manager Console we now provide more information to help with debugging.
Other notable changes in EF 4.3 include:
- Removal of EdmMetadata table. If you allow Code First to create a database by simply running your application (without using Migrations) the creation is now performed as an Automatic Migration. You can then enable migrations and continue evolving your database using migrations.
- Bug fix for GetDatabaseValues. In earlier releases this method would fail if your entity classes and context were in different namespaces. This issue is now fixed and the classes donât need to be in the same namespace to use GetDatabaseValues.
- Bug fix to support Unicode DbSet names. In earlier releases you would get an exception when running a query against a DbSet that contained some Unicode characters. This issue is now fixed.
- Data Annotations on non-public properties. Code First will not include private, protected or internal properties by default. If you manually include them in your model Code First used to ignore any Data Annotations on those members. This is now fixed and Code First will process the Data Annotations.
- More configuration file settings. Weâve enabled more Code First related settings to be specified in the App/Web.config file. This gives you the ability to set the default connection factory and database initializers from the config file. You can also specify constructor arguments to be used when constructing these objects. More details are available in the EF 4.3 Configuration File Settings blog post.
Getting Started
You can get EF 4.3 Beta 1 by installing the latest pre-release version of the EntityFramework NuGet package.
You will need NuGet 1.6 installed and specify the âIncludePrerelease flag at the Package Manager Console to get this pre-release version. Pre-release packages can only be installed from the Package Manager Console.
There are two walkthroughs for EF 4.3 Beta 1. One focuses on the no-magic workflow that uses a code-based migration for every change. The other looks at using automatic migrations to avoid having lots of code in you project for simple changes.
Upgrading From âCode First Migrations Beta 1â
If you have Code First Migrations Beta 1 installed you will need to uninstall the EntityFramework.Migrations package by running âUninstall-Package EntityFramework.Migrationsâ in Package Manager Console.
You can then install EF 4.3 Beta 1 using the âInstall-Package EntityFramework âIncludePrereleaseâ command.
You will need to close and re-open Visual Studio after installing the new package, this is required to unload the old migrations commands.
RTM Timeline
We are planning for this to be the last pre-release version of migrations and are still on-track to get a full supported, go-live, release of EF 4.3 published this quarter (first quarter of 2012).
MSDeploy Provider Update
We originally blogged about our plans to deliver an MSDeploy provider that could be used to apply migrations to a remote server. After many long hours iterating on this and working with the MSDeploy team weâve concluded that we canât deliver a good MSDeploy story for Migrations at this stage.
The primary issues arise from us needing to execute code from your application assemblies on the remote server, in order to calculate the SQL to apply to the database. This is a requirement that other MSDeploy providers have not had in the past. We are going to continue working with the MSDeploy team to see if we can deliver something in the future, but unfortunately we wonât be shipping an MSDeploy provider in the immediate future.
If you are able to connect to the remote database from the machine you are deploying from, then you can use the Update-Database.exe command line tool to perform the upgrade process. You can also use the System.Data.Entity.Migrations.DbMigrator class to write your own code that performs the migration process.
EF 5.0 (Enum support is coming⊠finally!)
Weâve been working on a number of features that required updates to some assemblies that are still part of the .NET Framework. These features include enums, spatial data types and some serious performance improvements.
As soon as the next preview of the .NET Framework 4.5 is available we will be shipping EF 5.0 Beta 1, which will include all these new features.
This is a preview of features that will be available in future releases and is designed to allow you to provide feedback on the design of these features. It is not intended or licensed for use in production. If you need assistance we have an Entity Framework Pre-Release Forum.
ADO.NET Entity Framework Team
EF 4.3 Beta 1: Code-Based Migrations Walkthrough
We have released the final preview of the Code First Migrations work as part of Entity Framework 4.3 Beta 1.
This post will provide an overview of the functionality that is available inside of Visual Studio for interacting with migrations. We will focus on the code-based workflow for using migrations. In this workflow each change is written out to a code-based migration that resides in your project.
There is a separate EF 4.3 Beta 1: Automatic Migrations Walkthrough that shows how this same set of changes can be applied using a mixture of code-based and automatic migrations.
This post assumes you have a basic understanding of Code First, if you are not familiar with Code First then please complete the Code First Walkthrough.
Building an Initial Model
Before we start using migrations we need a project and a Code First model to work with. For this walkthrough we are going to use the canonical Blog and Post model.
- Create a new MigrationsCodeDemo Console application.
. - Add the latest prerelease version of the EntityFramework NuGet package to the project.
- Tools â> Library Package Manager â> Package Manager Console.
- Run the âInstall-Package EntityFramework âIncludePrereleaseâ command.
.
- Add a Model.cs class with the code shown below. This code defines a single Blog class that makes up our domain model and a BlogContext class that is our EF Code First context.
using System.Data.Entity; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity.Infrastructure; namespace MigrationsCodeDemo { public class BlogContext : DbContext { public DbSet<Blog> Blogs { get; set; } } public class Blog { public int BlogId { get; set; } public string Name { get; set; } } }
Enabling Migrations
Now that we have a Code First model letâs enable Migrations to work with our context.
- Run the âEnable-Migrationsâ command in Package Manager Console.
. - This command has added a Migrations folder to our project. At the moment this folder just contains a single Configuration class. The Configuration class allows you to configure how Migrations behaves for your context.
Because there is just a single Code First context in your project, Enable-Migrations has automatically filled in the context type in the base class and Seed method for you.namespace MigrationsCodeDemo.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<MigrationsCodeDemo.BlogContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(MigrationsCodeDemo.BlogContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
Our First Migration
Code First Migrations has two commands that you are going to become familiar with. Add-Migration will scaffold the next migration based on changes you have made to your model. Update-Database will apply any pending changes to the database.
- We havenât generated any migrations yet so this will be our initial migration that creates the first set of tables (in our case thatâs just the Blogs table). We can call the Add-Migration command and Code First Migrations will scaffold a migration for us with its best guess at what we should do to bring the database up-to-date with the current model.
The Add-Migration command allows us to give these migrations a name, letâs just call ours MyFirstMigration.- Run the âAdd-Migration MyFirstMigrationâ command in Package Manager Console.
.
- Run the âAdd-Migration MyFirstMigrationâ command in Package Manager Console.
- In the Migrations folder we now have a new MyFirstMigration migration. The migration is pre-fixed with a timestamp to help with ordering.
namespace MigrationsCodeDemo.Migrations { using System.Data.Entity.Migrations; public partial class MyFirstMigration : DbMigration { public override void Up() { CreateTable( "Blogs", c => new { BlogId = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.BlogId); } public override void Down() { DropTable("Blogs"); } } } - We could now edit or add to this migration but everything looks pretty good. Letâs use Update-Database to apply this migration to the database.
- Run the âUpdate-Databaseâ command in Package Manager Console.
.
- Run the âUpdate-Databaseâ command in Package Manager Console.
- Code First Migrations has now created a MigrationsCodeDemo.BlogContext database on our local SQL Express instance. We could now write code that uses our BlogContext to perform data access against this database.
Customizing Migrations
So far weâve generated and run a migration without making any changes. Now letâs look at editing the code that gets generated by default.
- Itâs time to make some more changes to our model, letâs introduce a Blog.Rating property and a new Post class.
public class Blog { public int BlogId { get; set; } public string Name { get; set; } public int Rating { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } [MaxLength(200)] public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } - Letâs use the Add-Migration command to let Code First Migrations scaffold its best guess at the migration for us. Weâre going to call this migration MySecondSetOfChanges.
- Run the âAdd-Migration MySecondSetOfChangesâ command in Package Manager Console.
.
- Run the âAdd-Migration MySecondSetOfChangesâ command in Package Manager Console.
- Code First Migrations did a pretty good job of scaffolding these changes, but there are some things we might want to change:
- First up, letâs add a unique index to Posts.Title column.
- Weâre also adding a non-nullable Blogs.Rating column, if there is any existing data in the table it will get assigned the CLR default of the data type for new column (Rating is integer, so that would be 0). But we want to specify a default value of 3 so that existing rows in the Blogs table will start with a decent rating.
(These changes to the scaffolded migration are highlighted)
namespace MigrationsCodeDemo.Migrations { using System.Data.Entity.Migrations; public partial class MySecondSetOfChanges : DbMigration { public override void Up() { CreateTable( "Posts", c => new { PostId = c.Int(nullable: false, identity: true), Title = c.String(maxLength: 200), Content = c.String(), BlogId = c.Int(nullable: false), }) .PrimaryKey(t => t.PostId) .ForeignKey("Blogs", t => t.BlogId, cascadeDelete: true) .Index(t => t.BlogId) .Index(p => p.Title, unique: true); AddColumn("Blogs", "Rating", c => c.Int(nullable: false, defaultValue: 3)); } public override void Down() { DropIndex("Posts", new[] { "BlogId" }); DropForeignKey("Posts", "BlogId", "Blogs"); DropColumn("Blogs", "Rating"); DropTable("Posts"); } } }
- Our edited migration is looking pretty good, so letâs use Update-Database to bring the database up-to-date. This time letâs specify the âVerbose flag so that you can see the SQL that Code First Migrations is running.
- Run the âUpdate-Database âVerboseâ command in Package Manager Console.
So far we have just looked at migration operations that donât change or move any data, now letâs look at something that needs to move some data around. There is no native support for data motion yet, but we can run some arbitrary SQL commands at any point in our script.
- Letâs add a Post.Abstract property to our model. Later, weâre going to pre-populate the Abstract for existing posts using some text from the start of the Content column.
public class Post { public int PostId { get; set; } [MaxLength(200)] public string Title { get; set; } public string Content { get; set; } public string Abstract { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } - Letâs use the Add-Migration command to let Code First Migrations scaffold its best guess at the migration for us. Weâre going to call this migration AddPostAbstract.
- Run the âAdd-Migration AddPostAbstractâ command in Package Manager Console.
- Run the âAdd-Migration AddPostAbstractâ command in Package Manager Console.
- The generated migration takes care of the schema changes but we also want to pre-populate the Abstract column using the first 100 characters of content for each post. We can do this by dropping down to SQL and running an UPDATE statement after the column is added.
namespace MigrationsCodeDemo.Migrations { using System.Data.Entity.Migrations; public partial class AddPostAbstract : DbMigration { public override void Up() { AddColumn("Posts", "Abstract", c => c.String()); Sql("UPDATE Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL"); } public override void Down() { DropColumn("Posts", "Abstract"); } } } -
Our edited migration looks good, so letâs use Update-Database to bring the database up-to-date. Weâll specify the âVerbose flag so that we can see the SQL being run against the database.
- Run the âUpdate-Database âVerboseâ command in Package Manager Console.
Migrate to a Specific Version (Including Downgrade)
So far we have always upgraded to the latest migration, but there may be times when you want upgrade/downgrade to a specific migration.
- Letâs say we want to migrate our database to the state it was in after running our MyFirstMigration migration. We can use the âTargetMigration switch to downgrade to this migration.
- Run the âUpdate-Database âTargetMigration:"MyFirstMigration"â command in Package Manager Console.
This command will run the Down script for our AddBlogAbstract and MySecondSetOfChanges migrations. If you want to roll all the way back to an empty database then you can use the Update-Database âTargetMigration:"0" command.
Getting a SQL Script
Now that we have performed a few iterations on our local database letâs look at applying those same changes to another database.
If another developer wants these changes on their machine they can just sync once we check our changes into source control. Once they have our new migrations they can just run the Update-Database command to have the changes applied locally. However if we want to push these changes out to a test server, and eventually production, we probably want a SQL script we can hand off to our DBA.
- Now letâs run the Update-Database command but this time weâll specify the âScript flag so that changes are written to a script rather than applied. Weâll also specify a source and target migration to generate the script for. We want a script to go from an empty database (migration â0â) to the latest version (migration âAddPostAbstractâ).
Note: If you donât specify a target migration, Migrations will use the latest migration as the target.
- Run the âUpdate-Database -Script -SourceMigration:"0" -TargetMigration:"AddPostAbstract"â command in Package Manager Console.
.
- Run the âUpdate-Database -Script -SourceMigration:"0" -TargetMigration:"AddPostAbstract"â command in Package Manager Console.
- Code First Migrations will run the migration pipeline but instead of actually applying the changes it will write them out to a .sql file for you. Once the script is generated, it is opened for you in Visual Studio, ready for you to view or save.
NOTE: There are a number of bugs in the scripting functionality in EF 4.3 Beta1 that prevent you generating a script starting from a migration other than an empty database. These bugs will be fixed in the final RTM.
Summary
In this walkthrough you saw how to scaffold, edit and run code-based migrations to upgrade and downgrade your database. You also saw how to get a SQL script to apply migrations to a database.
Rowan Miller
Program Manager
ADO.NET Entity Framework
EF 4.3 Beta 1: Automatic Migrations Walkthrough
We have released the final preview of the Code First Migrations work as part of Entity Framework 4.3 Beta 1.
This post will provide an overview of the functionality that is available inside of Visual Studio for interacting with migrations. We will focus on the workflow that combines automatic and code-based migrations. In this workflow most changes can be automatically calculated and applied. More complex changes are written out to code-based migrations that reside in your project.
There is a separate EF 4.3 Beta 1: Code-Based Migrations Walkthrough that shows how this same set of changes can be applied using purely code-based migrations.
This post assumes you have a basic understanding of Code First, if you are not familiar with Code First then please complete the Code First Walkthrough.
Building an Initial Model
Before we start using migrations we need a project and a Code First model to work with. For this walkthrough we are going to use the canonical Blog and Post model.
- Create a new MigrationsAutomaticDemo Console application.
. - Add the latest prerelease version of the EntityFramework NuGet package to the project.
- Tools â> Library Package Manager â> Package Manager Console.
- Run the âInstall-Package EntityFramework âIncludePrereleaseâ command.
.
- Add a Model.cs class with the code shown below. This code defines a single Blog class that makes up our domain model and a BlogContext class that is our EF Code First context.
using System.Data.Entity; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity.Infrastructure; namespace MigrationsAutomaticDemo { public class BlogContext : DbContext { public DbSet<Blog> Blogs { get; set; } } public class Blog { public int BlogId { get; set; } public string Name { get; set; } } }
Enabling Migrations
Now that we have a Code First model, letâs enable Migrations to work with our context.
- Run the âEnable-Migrationsâ command in Package Manager Console.
. - This command has added a Migrations folder to our project. At the moment this folder just contains a single Configuration class. The Configuration class allows you to configure how migrations behaves for your context.
Because there is just a single Code First context in your project, Enable-Migrations has automatically filled in the context type in the base class and Seed method for you.
Weâll just edit the Configuration class to enable automatic migrations (highlighted below).
namespace MigrationsAutomaticDemo.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<MigrationsAutomaticDemo.BlogContext> { public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed(MigrationsAutomaticDemo.BlogContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
Our First Automatic Migration
Code First Migrations has two commands that you are going to become familiar with. Add-Migration will scaffold a code-based migration based on changes you have made to your model. Update-Database will apply any pending changes to the database. We are going to avoid using Add-Migration (unless we really need to) and focus on letting Code First Migrations automatically calculate and apply the changes.
- Letâs use Update-Database to get Code First Migrations to push our model to the database.
- Run the âUpdate-Databaseâ command in Package Manager Console.
.
- Run the âUpdate-Databaseâ command in Package Manager Console.
- Code First Migrations has now created a MigrationsAutomaticDemo.BlogContext database on our local SQL Express instance. We could now write code that uses our BlogContext to perform data access against this database.
Our Second Automatic Migration
Letâs make another change and let Code First Migrations automatically push the changes to the database for us.
- Letâs introduce a new Post class.
public class Blog { public int BlogId { get; set; } public string Name { get; set; }
public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } [MaxLength(200)] public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } - Letâs use Update-Database to bring the database up-to-date. This time letâs specify the âVerbose flag so that you can see the SQL that Code First Migrations is running.
- Run the âUpdate-Database âVerboseâ command in Package Manager Console.
.
Adding a Code Based MigrationNow letâs look at something we might want to use a code-based migration for.
- Letâs add a Blog.Rating property.
public class Blog { public int BlogId { get; set; } public string Name { get; set; } public int Rating { get; set; }
public List<Post> Posts { get; set; } } - We could just run Update-Database to push these changes to the database. However, were adding a non-nullable Blogs.Rating column, if there is any existing data in the table it will get assigned the CLR default of the data type for new column (Rating is integer, so that would be 0). But we want to specify a default value of 3 so that existing rows in the Blogs table will start with a decent rating.
Letâs use the Add-Migration command to write this change out to a code-based migration so that we can edit it. The Add-Migration command allows us to give these migrations a name, letâs just call ours MyFirstCodeMigration.- Run the âAdd-Migration MyFirstCodeMigrationâ command in Package Manager Console.
.
- Run the âAdd-Migration MyFirstCodeMigrationâ command in Package Manager Console.
- In the Migrations folder we now have a new MyFirstCodeMigration migration. The migration is pre-fixed with a timestamp to help with ordering. Letâs edit the generated code to specify a default value of 3 for Blog.Rating.
The migration also has a code-behind file that captures some metadata. This metadata will allow Code First Migrations to replicate the automatic migrations we performed before this code-based migration. This is important if another developer wants to run our migrations or when itâs time to deploy our application.
namespace MigrationsAutomaticDemo.Migrations { using System.Data.Entity.Migrations; public partial class MyFirstCodeMigration : DbMigration { public override void Up() { AddColumn("Blogs", "Rating", c => c.Int(nullable: false, defaultValue: 3)); } public override void Down() { DropColumn("Blogs", "Rating"); } } } - Our edited migration is looking pretty good, so letâs use Update-Database to bring the database up-to-date.
- Run the âUpdate-Databaseâ command in Package Manager Console.
Back to Automatic Migrations
Fortunately we donât have to keep using code-based migrations now, we can switch back to automatic migrations for our simpler changes. Code First Migrations will take care of performing the automatic and code-based migrations in the correct order based on the metadata it is storing in the code-behind file for each code-based migration.
- Letâs add a Post.Abstract property to our model.
public class Post { public int PostId { get; set; } [MaxLength(200)] public string Title { get; set; } public string Content { get; set; } public string Abstract { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } - Letâs use Update-Database to get Code First Migrations to push this change to the database using an automatic migration.
- Run the âUpdate-Databaseâ command in Package Manager Console.
Data Motion / Custom SQL
So far we have just looked at migration operations that can leave all the data in place, now letâs look at something that needs to move some data around. There is no native support for data motion yet, but we can run some arbitrary SQL commands at any point in our script.
We just added the Abstract column. Letâs pre-populate it for existing posts using text from the Content column.
- Use the Add-Migration command to let Code First Migrations add an empty migration for us. Weâre going to call this migration PopulatePostAbstract.
(The migration will be empty because there are no pending model changes that havenât been applied to the database)
- Run the âAdd-Migration PopulatePostAbstractâ command in Package Manager Console.
- Run the âAdd-Migration PopulatePostAbstractâ command in Package Manager Console.
- Update the migration to run some custom SQL that will populate the Abstract column.
namespace MigrationsAutomaticDemo.Migrations { using System.Data.Entity.Migrations; public partial class PopulatePostAbstract : DbMigration { public override void Up() { Sql("UPDATE dbo.Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL"); } public override void Down() { } } } -
Our edited migration looks good, so letâs use Update-Database to bring the database up-to-date. Weâll specify the âVerbose flag so that we can see the SQL being run against the database.
- Run the âUpdate-Database âVerboseâ command in Package Manager Console.
Migrate to a Specific Version (Including Downgrade)
So far we have always upgraded to the latest migration, but there may be times when you want upgrade/downgrade to a specific migration.
- Letâs say we want to migrate our database to the state it was in after running our MyFirstCodeMigration migration. We can use the âTargetMigration switch to downgrade to this migration. This is going to cause some columns that were added as part of an automatic migration to be dropped automatically on the way down. Code First Migrations wonât let this happen without you knowing about it, so we need to specify the âForce switch to acknowledge that we are OK with the potential data loss.
- Run the âUpdate-Database âTargetMigration:"MyFirstCodeMigration" âForceâ command in Package Manager Console.
This command will run the Down script for our PopulatePostAbstract migration, then use the automatic pipeline to revert the addition of the Abstract column.
If you want to roll all the way back to an empty database then you can use the Update-Database âTagetMigration:"0" command.
Getting a SQL Script
Now that we have performed a few iterations on our local database letâs look at applying those same changes to another database.
If another developer wants these changes on their machine they can just sync once we check our changes into source control. Once they have our new migrations they can just run the Update-Database command to have the changes applied locally. However if we want to push these changes out to a test server, and eventually production, we probably want a SQL script we can hand off to our DBA.
- Now letâs run the Update-Database command but this time weâll specify the âScript flag so that changes are written to a script rather than applied. Weâll also specify a source migration to generate the script from. We want a script to go from an empty database (migration â0â) to the latest version.
Note: You can also specify a target migration to generate a script to the database state at the end of a code-based migration. If you donât specify a target migration, Migrations will use the latest version as the target (including any automatic migrations that have been applied since the last code-based migration).
- Run the âUpdate-Database -Script -SourceMigration:"0"â command in Package Manager Console.
.
- Run the âUpdate-Database -Script -SourceMigration:"0"â command in Package Manager Console.
- Code First Migrations will run the migration pipeline but instead of actually applying the changes it will write them out to a .sql file for you. Once the script is generated, it is opened for you in Visual Studio, ready for you to view or save.
NOTE: There are a number of bugs in the scripting functionality in EF 4.3 Beta1 that prevent you generating a script starting from a migration other than an empty database. These bugs will be fixed in the final RTM.
In this walkthrough you saw how to use automatic migrations to push model changes to the database. You saw how to scaffold and run code-based migrations when you need more control. You also saw how to upgrade and downgrade your database. Finally we looked at how to get a SQL script that represents the pending changes to a database.
Rowan Miller
Program Manager
ADO.NET Entity Framework
EF 4.3 Configuration File Settings
We recently released Entity Framework 4.3 Beta 1 which includes the ability to configure more DbContext and Code First related settings from your applications Web.config or App.config file.
These Settings are Optional
Code First and the DbContext API follow a âconvention over configurationâ principle. All the settings discussed in this post have a default behavior, you only need to worry about changing the setting when the default no longer satisfies your requirements.
All of these settings can also be applied using code. The configuration file option allows these settings to be easily changed during deployment without updating your code.
The Entity Framework Configuration Section
In earlier versions of Entity Framework you could set the database initializer for a context using the appSettings section of the configuration file. In EF 4.3 we are introducing the custom entityFramework section to handle the new settings. Entity Framework will still recognize database initializers set using the old format, but we recommend moving to the new format where possible.
The entityFramework section was automatically added to the configuration file of your project when you installed the EntityFramework NuGet package.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration,
visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
</configuration>Connection Strings
Setting a connection string for a context uses the same syntax as previous releases of Entity Framework.
Code First uses normal ADO.NET connection strings. For example:
<connectionStrings>
<add name="BlogContext"
providerName="System.Data.SqlClient"
connectionString="Server=.\SQLEXPRESS;Database=Blogging;Integrated Security=True;"/>
</connectionStrings>
This post provides more details on how Code First determines the database to be used, including connection strings in the configuration file.
The Database First and Model First approaches with an EDMX file use special EF connection strings. For example:
<connectionStrings>
<add name="BlogContext"
connectionString="metadata=res://*/BlogModel.csdl|
res://*/BlogModel.ssdl|
res://*/BlogModel.msl;
provider=System.Data.SqlClient;
provider connection string=
"data source=.\SQLEXPRESS;
initial catalog=Blogging;
integrated security=True;
multipleactiveresultsets=True;""
providerName="System.Data.EntityClient" />
</connectionStrings>
Connection strings go in the standard connectionStrings element and do not require the new entityFramework section.
Code First Default Connection Factory
The new configuration section allows you to specify a default connection factory that Code First should use to locate a database to use for a context. The default connection factory is only used when no connection string has been added to the configuration file for a context.
To set a connection factory, you specify the assembly qualified type name in the deafultConnectionFactory element.
Note: An assembly qualified name is the namespace qualified name, followed by a comma, then the assembly that the type resides in. You can optionally also specify the assembly version, culture and public key token.
Here is an example of setting your own default connection factory:
<entityFramework>
<defaultConnectionFactory type="MyNamespace.MyCustomFactory, MyAssembly"/>
</entityFramework>
The above example requires the custom factory to have a parameterless constructor. If needed, you can specify constructor parameters using the parameters element.
For example, the SqlCeConnectionFactory, that is included in Entity Framework, requires you to supply a provider invariant name to the constructor. The provider invariant name identifies the version of SQL Compact you want to use. The following configuration will cause contexts to use SQL Compact version 4.0 by default.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
If you donât set a default connection factory, Code First uses the SqlConnectionFactory, pointing to .\SQLEXPRESS. SqlConnectionFactory also has a constructor that allows you to override parts of the connection string. If you want to use a SQL Server instance other than .\SQLEXPRESS you can use this constructor to set the server.
The following configuration will cause Code First to use a LocalDB instance for contexts that donât have an explicit connection string set.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
By default, itâs assumed that constructor arguments are of type string. You can use the type attribute to change this.
<parameter value="2" type="System.Int32" />
Database Initializers
Database initializers are configured on a per-context basis. They can be set in the configuration file using the context element. This element uses the assembly qualified name to identify the context being configured.
By default, Code First contexts are configured to use the CreateDatabaseIfNotExists initializer. There is a disableDatabaseInitialization attribute on the context element that can be used to disable database initialization.
For example, the following configuration disables database initialization for the Blogging.BlogContext context defined in MyAssembly.dll.
<contexts> <context type=" Blogging.BlogContext, MyAssembly" disableDatabaseInitialization="true" /> </contexts>
You can use the databaseInitializer element to set a custom initializer.
<contexts>
<context type=" Blogging.BlogContext, MyAssembly">
<databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly" />
</context>
</contexts>
Constructor parameters use the same syntax as default connection factories.
<contexts>
<context type=" Blogging.BlogContext, MyAssembly">
<databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly">
<parameters>
<parameter value="MyConstructorParameter" />
</parameters>
</databaseInitializer>
</context>
</contexts>
You can configure one of the generic database initializers that are included in Entity Framework. The type name should specify your context as the TContext generic. The type attribute uses the .NET Framework format for generic types.
The following configuration sets the DropCreateDatabaseAlways<TContext> initializer for the BlogContext.
Note: The type name is wrapped in the example but must appear on a single line in your configuration file.
<contexts>
<context type=" Blogging.BlogContext, MyAssembly">
<databaseInitializer type="System.Data.Entity.DropCreateDatabaseAlways`1[
[Blogging.BlogContext, MyAssembly]], EntityFramework" />
</context>
</contexts>
If you are using Code First Migrations, you can configure the database to be migrated automatically using the MigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration> initializer.
Note: The type name is wrapped in the example but must appear on a single line in your configuration file.
<contexts>
<context type="Blogging.BlogContext, MyAssembly">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[Blogging.BlogContext,
MyAssembly], [Blogging.Migrations.Configuration, MyAssembly]], EntityFramework" />
</context>
</contexts>
Summary
In this walkthrough you saw how to use the configuration file to set connection strings, default connection factory and database initializers.
Rowan Miller
Program Manager
ADO.NET Entity Framework
SQL Azure Federations and the Entity Framework
The recent SQL Azure Q4 2011 Service Release includes the new feature SQL Azure Federations which enables greater scalability and performance from the database tier of your application through horizontal partitioning. One or more tables within a database are split by row and partitioned across multiple databases (Federation members). This type of horizontal partitioning is often referred to as âshardingâ. Detailed information on the SQL Azure Federations feature is available here.
The current release of Entity Framework can be used to work with SQL Azure Federations, however a federated database cannot be created by the Entity Framework. Our Customer Advisory Team has started a series of blog posts with the goal of providing guidance around common scenarios and issues that arise when using the Entity Framework with SQL Azure Federations.
The first blog post in this series, SQL Azure Federations with Entity Framework Code-First, is a great getting started guide. It explains the correct procedure to submit the USE FEDERATION statement before sending queries to the database via the Entity Framework (query execution or update operations).
The next post, Understanding SQL Azure Federations No-MARS Support and Entity Framework, explains the impact of the lack of support for MARS on Entity Framework applications.
We are working with the Customer Advisory Team to continue adding posts to this series. While these blog posts provide concrete scenarios detailed walkthroughs and code samples, here are some general guidelines/considerations:
- The Entity Framework based application needs to be aware and manage the access to the different federation members. What this means is that the application would have to explicitly open the store connection with which the context is associated and issue the âUSE FEDERATIONâ statement to connect to the correct federation member before interacting with the database via the Entity Framework.
- Any needed database transaction would have to be started after the âUSE FEDERATIONâ statement is issued. This is because federated databases do not support the âUSE FEDERATIONâ statement in a transaction.
- Any connection retries would also need to be handled by the application.
- Instances of the context class should not span across federation members. In general, this also means that all changes managed by the context should be associated with a single federation member. This is because at the time SaveChanges is invoked, it would issue the corresponding database data modification operations only to the federation member to which the associated store connection currently points.
In the future, our plan is to provide more integrated support for SQL Azure Federations. We would love to hear your experiences on using the Entity Framework with federated databases as well as your suggestions on how we can improve it.
ADO.NET Entity Framework Team
Get your SQL Server database ready for SQL Azure!
One of our lab project teams was pretty busy while the rest of us were taking a break between Christmas and New Yearâs here in Redmond. On January 3rd, their new lab went live: Microsoft Codename "SQL Azure Compatibility Assessment". This lab is an experimental cloud service targeted at database developers and admins who are considering migrating existing SQL Server databases into SQL Azure databases and want to know how easy or hard this process is going to be. SQL Azure, as you may already know, is a highly available and scalable cloud database service delivered from Microsoftâs datacenters. This lab helps in getting your SQL Server database cloud-ready by pointing out schema objects which are not supported in SQL Azure and need to be changed prior to the migration process. So if you are thinking about the cloud again coming out of a strong holiday season where some of your on-premises databases were getting tough to manage due to increased load, this lab may be worth checking out.
There are two steps involved in this lab:
- You first need to generate a .dacpac file from the database youâd like to check on with SQL Server Data Tools (SSDT) CTP4. SQL Server 2005, 2008, 2008 R2, 2012 (CTP or RC0) are supported.
- Next, you upload your .dacpac to the lab cloud service, which returns an assessment report, listing the schema objects that need to change before you can move that database to SQL Azure.
You find more information on the lab page for this project and in the online documentation. A step-by-step video tutorial will walk you through the process. Of course, we would love to hear feedback from you!
And weâre always interested in suggestions or ideas for other things youâd like to see on http://wwwsqlazurelabs.com. You can use the feedback buttons on that page and send us a note, or visit http://www.mygreatwindowsazureidea.com/ and enter a new idea into any of the specific voting forums that are available there. Thereâs a dedicated voting forum for SQL Azure and many of its subareas. You can also place a vote for ideas that were posted if you spot something that matters to you. We appreciate your input! Follow @SQLAzureLabs on Twitter for news about new labs.
-- Christina Storm (@chrissto)
Principal Program Manager, SQL Azure Labs