This one had me a little stumped, and as usual, there are not enough examples in the Microsoft documentation to be very helpful. I’m using EntityFramework CodeFirst with Visual Studio 2011.  Let’s assume you create a class as follows:

 

public class CongressNumber
    {
        [Key]
        public int CongressNumberValue { get; set; }
    }

Then, you manually set the value of CongressNumberValue to 112.  I’d certainly think that is a reasonable thing to do. I know that the Microsoft guys often special case Id or id, but hard to believe they would take something like CongressNumberValue and assume I meant that to be an autogenerating Identity column.  Well, it seems they do that and the doc’s don’t even mention it. 

After first, finding the page on annotations, I discovered that what we really need to set is this to have it work as we want (with no identity key generation).

 public class CongressNumber
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CongressNumberValue { get; set; }
    }

I found this after drilling down some in there doc.  What surprises me is that no where does it mention that if you have a string, that does not get database generated, but if you have an int, that does.  I wonder what happens if you have a Guid? (I’ll leave that up to someone who wants to use a guid).

I would have loved to put in my own comments on the page: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.databasegeneratedoption(v=vs.103).aspx but there was no user comment section.  Oh well.

To be fair, on the page: http://msdn.microsoft.com/en-us/library/gg197525(v=vs.103).aspx it does explain about identity and integers but when I had my issue, I was already on the detail page.  Seems to me the detail page should have more information on it than the summary page that leads in.  The only reason I found it was because while writing this post, I went back to get the proper links.

 

image

HTH’s.

Problem

So, if you have been doing development with Visual Studio 2010, Entity Framework CodeFirst, SqlServer or SqlServerCE for any amount of time, you’ll quickly run into the problem that the database can not be reinitialized because it is open.  Basically, the scenario is this.

1)  Put in your Global.asax.cs file a line that always recreates the database (naturally because you are in a development mode and as you constantly change your model and seed data).  The line is something like this:  Database.SetInitializer(new DropCreateDatabaseAlways<SiteDB>());

2)  Run your application with something like Debug/Run (All is fine)

3)  Go into the database browser (either in Visual Studio or Enterprise Manager)  and look at some data.

4)  Run your application again and you will get this error: “[SqlException (0x80131904): Cannot drop database "NewYorkTimesDb" because it is currently in use.]”.  This is because your database browser has a connection to the database and until it is dropped, you can not drop the catalog.

 

image

 

Solutions

 

The easiest and guaranteed to work solution is just to restart your SqlServer database server (control panel, services).  This is what I use to do but finally got tired of that because it takes about 20 seconds and, well, I’m very impatient.

The other solution I found in the forums (can’t find the link right now) is to execute the following script from the master database catalog:

use master
ALTER DATABASE NewYorkTimesDb 
   SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
ALTER DATABASE NewYorkTimesDb SET MULTI_USER

Basically, just switching from multi-user to single-user and back clears the connections.

HTH’s!

I’ve been using EntityFramework’s CodeFirst 4.1 on a new project I’ve been working.  I plan to blog quite  bit about it, but in the mean time I just felt the need to share.  I’ve got some fairly complex code where I add an object tree to the database context (which turns into SqlServer data).  When I call db.SaveChanges(), I get an awesome error (see below) telling me exactly why it failed.

I’m currently on the honey moon with EF CodeFirst.  I only have about 10 tables (4 deep at most).  Life is good.

  
image

I’m always somewhat amazed when I read something from documentation that is not straight forward and it actually works.  So amazed and excited that I often feel the need to blog about it.

So, here is the problem.  I created a CodeFirst implementation of EntityFramework in Visual Studio and created a simple hierarchy in my data model.  That is, without showing all the code, here is what I have:

public class Person
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

public virtual List<EmailAddressInfo> EmailAddressInfoList { get; set; }
..
}

public class EmailAddressInfo
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

public string EmailAddress { get; set; }

}

public class EmailAccount
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
...
}

Now, if you execute a LINQ command like the following:

var recs = (from data in db.Persons
select data);
foreach (var rec in recs)
{
foreach (var email in rec.EmailAddressInfoList)
{
Console.WriteLine(email);
}
}

You get the error:

Exception Details: System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.

 

image

 

To solve this, you need to tell EntityFramework/CodeFirst to include the EmailAddressInfoList in the query.  All you need to do is change the db.Persons to db.Persons.Include("EmailAddressInfoList") as follows:

 

var recs = (from data in db.Persons.Include("EmailAddressInfoList")
select data);

 

Then, it all works!

Hope this helps.

I’ve been struggling with getting the EF CodeFirst right so that it automatically generates foreign keys when the tables are created. I had noticed that there is interesting syntax you can put in to create these foreign keys, however it seemed that the relationships are known so CodeFirst should do that for you.  I won’t even bother to go through all the mistakes I made, but if you want to see one, you can check out my forum post where I ask for help.

I’m currently writing a series of articles on building a Sencha ExtJS application with Microsoft ASP.NET MVC3.  I use codefirst and at the moment I’m building a database of US Presidents and linking them to their Party (republican, democrat, etc.).  So, the important thing is to link from the Presidents table to the Party Table and also from the Party to the President.  Below is the code:

namespace SenchaDesignerExtension.Models
{
public class Party
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

[MaxLengthAttribute(40)]
public string Name { get; set; }
public virtual ICollection<President> Presidents { get; set; }
}

public class President
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

public virtual Party Party { get; set; }

public int PresidentNumber { get; set; }

[MaxLengthAttribute(20)]
public string FirstName { get; set; }
[MaxLengthAttribute(20)]
public string LastName { get; set; }
public bool Impeached { get; set; }
public DateTime TookOffice { get; set; }
public DateTime LeftOffice { get; set; }
public decimal Income { get; set; }
}
}

And, the repository is defined as follows:

public class USPresidentsDb : DbContext
{
public USPresidentsDb()
: base("name=USPresidents")
{
}

public DbSet<UserInfo> Users { get; set; }
public DbSet<President> Presidents { get; set; }
public DbSet<Party> Parties { get; set; }
...

 

Notice that in the party class, there is a virtual ICollection of Presidents, and notice in the President class, there is a virtual reference to the Party.  These combined make the relationship work and the foreign key created.

If I look in my SQL Database, you’ll see a new foreign key is automatically created for me as Party_id.

 

image

I’m not exactly sure how SqlExpressCE shows foreign keys, but I know it is there because when I try to delete a Party record that is associated with a President I get the following error:

 

image

which tells me there is a constraint called Party_Presidents (my foreign key).

 

So, it worked!  If you want to see the full source for this, keep an eye on the series of articles I’m now writing (only the first one is done, but probably, by the time you find this, I’ll have others done that include this Presidents example.  You can find the first one at the URL:  http://peterkellner.net/2011/11/04/building-an-senchas-extjs-4-0-mvc-application-with-microsofts-asp-net-mvc3-series-basics/

 

In May of 2009 I discovered some significant performance problems that I blogged about.  In summary, I had tracked it down to the issue of LINQ2SQ having to create a full expression tree on every instantiation of a LINQ2SQL query.  I’m not a compiler write kind of guy but do respect the complexity of that and doing things like building expression trees, but still this really sucked.  Using the compile syntax in LINQ2SQL is very awkward, and IMHO takes all the fun out of using LINQ2SQL.  If you don’t remember my post, here is the graph showing the evil happening.

 

image

So, what is a Microsoft MVP to do?  I complained to everyone at Microsoft I knew.  I made this my mission for about a year.  I was told time after time that the problem was hugely complicated and no one was working on making it any faster.  I just could not believe it because I felt this was such a barrier to success to LINQ2SQL type technology (now Entity Framework really) that Microsoft just could not ignore my findings.  I was actually surprised that I was the only one screaming about this.

Well, quietly, Microsoft has announced that in .Net Framework 4.5, Entity Framework will include “Auto-Compiled LINQ Queries”.  This is awesome!   When it comes out, I’ll be testing and it giving feedback.

For now, I’m a very happy camper.

 

image

Over the past couple years, the focus of the web development I’ve been doing involves building highly flexible, highly scalable and straight forward web sites to implement and maintain Line of Business (LOB) applications.  As you can probably tell from my posts, I’m very “practical” focused, and at the same time have a desire to build awesome web applications.

The technology pairing I’ve chosen is Microsoft’s .Net platform with MVC on the server, and ExtJS on the client.  Though it’s possible to still use ExtJS with standard html/aspx pages, I’ve found the best combination is to use 100% JavaScript on the client (ExtJS) and have all the server side technology be 100% service based.  I’ve used LINQ2SQL extensively as well as Entity Framework in the latest Visual Studio 2010 release.

The learning curve was quite steep to actually be able to efficiently build highly flexible, highly scalable applications using these technologies, but now that I know it, I wouldn’t have it any other way.

I’m considering putting together a series of 4 Day Classes around the country (or even world) that would basically teach people the methods and patterns I’ve learned and essentially leap frog a development team into being able to quickly do what it has taken me years to figure out.  I’ve been fortunate enough to know the top 1% instructors and I’m sure with the right incentive, can get them to join me in both putting together these classes as well as teaching them.

(more…)

  Title Of Each Article Video Included With Each Post
Part 1 Introduction To RIA Services In Silverlight (This Article) 7 Minutes
Part 2 Basic RIA Services And DataGrid With  VS 2010 Tooling 14 Minutes
Part 3 Adding A DataGrid With Connect The Dots DataBinding in VS 2010 13 Minutes
Part 4 Adding a Navigation Page to a Silverlight Business Application Template 11 Minutes
Part 5 Adding Speakers Page Template With Converters In Visual Studio 2010 Beta2 11 Minutes
Part 6 Adding A Sessions Page That Includes a Query Parameter In Silverlight VS2010 Beta2 10 Minutes
Part 7 Basic Authentication and Authorization In RIA Services 5 Minutes

Get the Flash Player to see the wordTube Media Player.

This article is very short.  In the actual presentation, there was not much time to talk about this so a brief overview was done.  Basically, it’s all standard WCF stuff.  The idea is that the Silverlight Business Template adds logging in and supports Authentication just like an asp.net application does.  It uses the DomainDataSource to do the bridging between the silverlight clientside app, and the web application.  Authorization is built into the login module also so that you can assign attributes to your domainservice classes to restrict access.

(more…)

 

  Title Of Each Article Video Included With Each Post
Part 1 Introduction To RIA Services In Silverlight (This Article) 7 Minutes
Part 2 Basic RIA Services And DataGrid With  VS 2010 Tooling 14 Minutes
Part 3 Adding A DataGrid With Connect The Dots DataBinding in VS 2010 13 Minutes
Part 4 Adding a Navigation Page to a Silverlight Business Application Template 11 Minutes
Part 5 Adding Speakers Page Template With Converters In Visual Studio 2010 Beta2 11 Minutes
Part 6 Adding A Sessions Page That Includes a Query Parameter In Silverlight VS2010 Beta2 10 Minutes
Part 7 Basic Authentication and Authorization In RIA Services 5 Minutes


Get the Flash Player to see the wordTube Media Player.


In this section, we will talk about what happens when the users presses the “Sessions” hyperlink from the speakers page.  If you remember from the last article, we used a special converter on the Speakers.xaml page and bound that to the hyperlink titled sessions as shown below.

(more…)

  Title Of Each Article Video Included With Each Post
Part 1 Introduction To RIA Services In Silverlight (This Article) 7 Minutes
Part 2 Basic RIA Services And DataGrid With  VS 2010 Tooling 14 Minutes
Part 3 Adding A DataGrid With Connect The Dots DataBinding in VS 2010 13 Minutes
Part 4 Adding a Navigation Page to a Silverlight Business Application Template 11 Minutes
Part 5 Adding Speakers Page Template With Converters In Visual Studio 2010 Beta2 11 Minutes
Part 6 Adding A Sessions Page That Includes a Query Parameter In Silverlight VS2010 Beta2 10 Minutes
Part 7 Basic Authentication and Authorization In RIA Services 5 Minutes

Get the Flash Player to see the wordTube Media Player.

 

In this article, we will  build from scratch, using Visual Studio 2010 Beta 2 a simple application that lets us view Silicon Valley Code Camp Attendees that have authorized us to share their data.  We will be using no special RIA Services Visual Studio 2010 design tools to do this.  We will:

  • Create the Entity Framework Repository
  • Create the Domain Service
  • Wire up an Appropriate Get Method that Returns in IQueryable
  • Call From the Client Code the Domain Service
  • Show The Results
  • Observations

First, we need to create a new Visual Studio Project.  We do that by using the File/New Project and chose “Silverlight Business Application”.

(more…)

This series of video presentations goes through the process of building a Speaker and Sessions Viewer for Silicon Valley Code Camp’s data using Silverlight 4 and RIA Services (Using Visual Studio 2010 Beta 2).  It starts with a brief introduction of RIA Services and is followed by screen casts and blog posts the parallel each screen cast.

The actual presentation was done at the Microsoft office in San Francisco.

(more…)

 

You all know that I’ve blogged quite a bit about LINQ2SQL.  That technology has saved me a huge amount of programming effort verses using ado.net directly.  We all know that LINQ2SQL is really just a stepping stone to Entity Framework (EF), though Microsoft doesn’t quite say that.  I’m sure, based on how many people are using LINQ2SQL, it will live on and be supported for quite sometime.  Personally, I’ve been waiting for EF to become more mature and then, I assume I’ll start all my new projects with it (EF) and slowly migrate my old ones from LINQ2SQL to EF.  So, time for me to start taking EF more seriously.  It’s baked into the upcoming .net 4.0 and Visual Studio 2010 beta 2.  It’s obviously not done, but from what I’ve seen, when .net 4.0 releases, EF will be ready for prime time.

Now, for the review:

(more…)

© 2012 PeterKellner.net. All Rights Reserved