Monthly Archives: September 2007

Ripening the tomatoes

It has been an amazing summer for growing. there are still lots and lots of tomatoes in my garden. I’ve been picking the tomatoes before they are ripe and letting them finish in the sun. I decided that this will help the rest of the tomatoes that are still growing on the vines. I have a whole bunch in the dining room ready to be processed but waiting for this batch so I can do them all at once. There are a few different varieties.

Sharing Entity Framwork models between projects (or teams) when developing

The new Entity Framework tools create an EDMX file which contains all three models: Conceptual, Mapping and Storage, in one file. When your project is built, individual files are created for the models, in the [familiar to those who have been using Entity Framework already] CSDL (conceptual), MSL (mapping) and SSDL (storage) files.

The connection string used by the Entity Framework contains not only the database connection string, but a metadata parameter with pointers to the three mapping files separated by a pipe character.

The Default Locations

Assuming that you put your EDM in the main folder of your project, in Windows Forms, Console and Class Library projects, you will see by default:

connectionString=
metadata=.\Model.csdl|.\Model.ssdl|.\Model.msl;provider=System.Data.SqlClient;provider connection string=’Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorksLT_Data.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True'”

When the project is built, those 3 files will land in the debug or release folder of the BIN directory for the app.

In a web app, the default location is different:

connectionString=
“metadata=~/bin/Model1.csdl|~/bin/Model1.ssdl|~/bin/Model1.msl;provider=System.Data.SqlClient;provider connection string=’Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorksLT_Data.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True'”

This pushes the files into the bin folder of the site as well.

Sharing EDM with another project or another developer

If you have your EDM in it’s own project and then want to reference it from another project, you need to perform two steps.

1) Add a reference to the compiled DLL which represents the EDM.
2) Modify the config file of your consuming application to point to the location of the csdl, msl and ssdl files.

Here is an example of  a web.config’s connection string at design time that needs to use a model which is in a different project folder. I had to manually enter this long file path. Yucch.

connectionString=”metadata=C:\Documents and Settings\julie\My Documents\Visual Studio 2008\Projects\EFBeta2Windows\AdventureWorksModel\bin\Debug\Model.csdl|
 C:\Documents and Settings\julie\My Documents\Visual Studio 2008\Projects\EFBeta2Windows\AdventureWorksModel\bin\Debug\Model.ssdl|
 C:\Documents and Settings\julie\My Documents\Visual Studio 2008\Projects\EFBeta2Windows\AdventureWorksModel\bin\Debug\Model.msl;
provider=System.Data.SqlClient;
provider connection string=’Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorksLT_Data.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True'” providerName=”System.Data.EntityClient” />
   

There’s a better way

In the ADO.NET Orcas forums, Craig Lee pointed out that the build task for EDMDeploy which creates these files is placed in the project file and can be edited. I went looking.

You can get at it right in the UI for editing the project.

Go to the Compile tab, then to Build Events.

You can see the EdmxDeploy code in the Post-build event command line.

By editing, you can see the whole thing and the target directory parameter.

I changed the target to point to an existing (easy access for demos!) folder on my drive.

Then after I built the model project again, the csdl, msl and ssdl files were all in c:\efmodels\aw.

Now I can easily modify the metadata paths of any projects that consume my model to simple paths such as “C:\efmodels\aw\model.csdl”.

If I am in a team environment, then my files need to be available on a shared location or from source control.

EntityKey and ASP.NET ViewState

Just to see another aspect the before and after difference of serializable EntityKeys in the Beta2 of EntityFramework, I simply stored a single Customer entity into viewstate, posted back and then looked at the entity in debug to see that yes, the EntityKey is there.

I went back to my Beta1 VPC and when I try to add a single customer entity object to viewstate, I get all kinds of serialization errors. No point in analyzing them since it works now.

I’ll probably explore some asp.net databinding scenarios next.

Jersusalem Trail hike and lots of pretty berries I don’t want to eat

On Saturday, Rich and I hiked up the Jersusalem trail which is only a short drive from our house. It is one of the many trails that take you up to the Long Trail. This one lands about half way between the App Gap and Mt. Abe.

Alongo the way there were lots of berries growing, none which looked the least bit appetizing. So I took their pics and came home to find out what they were. i’ve only got one id’d so far. And I’m STILL trying to figure out what the flowers were that I saw on an early summer hike that are here. I think I saw them on a wildflower poster somewhere and tried to memorize the name, but forgot by the time I got home. uggh.

The first turns out to be a White Baneberry, aka “Doll’s eyes”, which I identified thanks George Africa’s blog post. George is one of those fairytale gardeners. You’ll see what I mean if you poke around his blog.

Here is a really unpalatable blue berry which really is probably just a dried up seed pod from whatever flower was here. The leaves are reminiscent of a bleeding heart.

This last one looks like maybe it’s some type of viburnum and it’s something I’ve seen frequently. I’ve just looked at pictures of many varieties, but can’t find one quite like this. So maybe it’s something else. but the most important thing is not to eat the darned things.

Speaking of eatingi things in the woods, the chanterelles have finally arrived! They were much later this year than the past few years. I’ve only had one sumptuous batch so far – about 2 pounds that I picked and brought to a recent party and cooked up in pounds of butter. Over the past few years, my skill as a chanterelle cook have definitely improved. High heat, loads of butter and lots of salt & pepper. Very French, just don’t tell my doctor. 😉

Entity framework Tools: Package Load Failure when opening up EDMX in designer (FAQs are coming)

In the forums, Craig Lee responds to the  problem reported in this thread:

We are planning on releasing an FAQ of known issues, but here is a preview to see if this helps you.

Issue
Visual Studio displays a Package Load Failure error message for Package ‘Microsoft.Data.Entity.Design.Package.MicrosoftDataEntityDesignPackage’ when you double-click on a .edmx file

Workaround

This issue is caused by earlier installations of the MCrit June CTP.

1.    If it is installed, uninstall the ADO.NET Entity Framework Tools CTP from “Add/Remove Programs” in control panel

2.    Use gacutil.exe to verify that the following DLLs are not in the GAC. 

a.    Microsoft.Data.Entity.Design.dll

b.    Microsoft.Data.Entity.Design.EntityDesigner.dll

c.    Microsoft.Data.Entity.Design.Package.dll

d.    Microsoft.Data.Tools.XmlDesignerBase.dll

3.    Use Regedit.exe to check for and remove the CodeBase value from the registry at:

a.    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Packages\{8889E051-B7F9-4781-BB33-2A36A9BDB3A5}

4.    Reinstall the the ADO.NET Entity Framework Tools CTP

 

Exploring EntityKeys, Web Services and Serialization a little further

I have not been able to stop thinking about EntityKeys, serialization and web services since my post about them yesterday, so I have done a little more experimentation tonight.

ObjectContext does have an AttachTo method. In my scenario of the incoming object from a web service client, the EntityKey is not available as part of the SalesOrderHeader entity because that is currently not being serialized as part of the entity. Note that this is a bug that the Entity Framework team is aware of and will fix.

While Attach allows you attach an entity that has a key, AttachTo does not require the EntityKey. However it does require that you know the name of the EntitySet.

In the type of testing scenario that I am working with , this is not a big problem.

While Attach would let me call

MyObjectContext.Attach(MyEntitythathasanEntityKey)

AttachTo has me call

MyObjectContext.Attach(MyKeylessEntity,”TheEntitySet”)

Once I do this, the EntityKey is created.

Note the contents of an entity key:

It has the name of the EntitySet in it. (I did not fix up the EntitySet names that the wizard created. I should have done this right after the wizard, and the new designer makes that really easy to do now.) That should be SalesOrderHeaders (plural)).

The EntitySet is nowhere else in the definition of my “incoming” SalesOrderHeader.

So if I didn’t happen to know the name of the EntitySet, I wouldn’t be able to attach it. If I want to have a generic updater, this could be a problem.

And a word or two hundred about concurrency:

The EntityKey itself has no impact on how to handle updates in the service.

As with LINQ to SQL, when I attach an object, it attaches as an unmodified entity. SaveChanges does nothing. The entity keeps track of original and modified values (which you can actually see if you create an ObjectStateEntry object from the entity). I actually tried attaching another instance of the object with different values, then attaching my incoming one to see if the 2nd instance would be seen as modified. No go. (Yah – grabbing at straws…and random ones at that!)

I tried calling Refresh with the ClientWins parameter (along with an array that contained my entity) to see if I could get the database to push it’s original values into the entity and somehow get the incoming values to magically become modified values. There have to be modified values to begin with for any of this to work. That doesn’t change anything because the state of the entity is still unmodified since the time I attached it.

The next thing I tried was updating the ModifiedTime property to see if kicking the ModifiedState of the entity would force all of my changes to get saved. Only ModifiedTime was saved, not the other values that were different.

The last thing I tried was, after attaching the entity, change the value using this funny method:

mySalesOrder.Comment=mySalesOrder.Comment

AND IT WORKED!

The entityState became modified and the Comment column was updated in the database.

So at this point, it still looks like there is no way around explicitly updating the entity properties in order to get them to be seen as modified. But I have no way of knowing WHICH of these things have been changed. Which leaves me a few options (probably more than just these three):

  • Update every property
  • Cache the entities when they are retrieved from the database (though I have to figure out what I want to cache… a dataset? an entire ObjectContext? … then I have to make decisions about keeping that refreshed).
  • Grab the current data from the database just before I want to update. There are also potential concurrency issues with this as well.
  • Iterate through each property and, using the ObjectStateEntry, set them as modified using the SetModifiedProperty, which takes the property name (string) as a parameter. I could do this in conjunction with data from the database or data from some cached store and only do this to properties that are different.

However all of these options seem to rely on knowing the name of the properties and I have not been able to find a way to programmatically discover them.

Therefore, it seems that I may have to go down one of these paths:

  1. Use reflection to iterate through all of the properties and update them. My feeling about having to go to these lengths is “just no!” Plus this will mean that every property will be seen as modified and will get updated.
  2. Write updaters for every entity that will explicitly set each property. That’s a crap load of data access code and not having to write a crap load of data access code is one of the benefits of Entity Framework.
  3. Hope and pray that the EntityFramework team can somehow give us a way of attaching an object for original and one for modified. LINQ to SQL has this.
  4. Wait for someone on the team to comment in my blog and show me the super easy obvious way that I have totally overlooked.

What’s a little funny to me is that Rick Strahl has had a similar conundrum with LINQ to SQL.

And I’m still only talking about full-on clientWins concurrency, so far.

Knocking off Danny Simmons Entity Framework Beta 2 List: #3 & #4: EntityKey Serialization and new Entity interfaces

The next things in the list of what’s new in EF Beta 2 that I have been experimenting with are:

  • Entity key serialization In previous CTPs EntityKey objects were not serializable, now they are.
  • Increased persistence ignorance in entity data classes We are continuing down the path toward true POCO and persistence ignorance.  To that end we have split the original IPOCO interface (IEntity) into two separate, more specific interfaces (IEntityWithKey and IEntityWithChangeTracker), we made IEntityWithKey optional (not implementing it has performance implications, but the scenario is supported), and many of the ObjectServices signatures have been modified to take instances of Object rather than IEntity which sets the stage for further progress here in future releases.
I’ve actually been playing with this for days but having a hard time with it. It turns out that while EntityKey objects, which are on their own are serializable, they are not being serialized as a property of an Entity. This is a bug (confirmed by Danny via email) and not the intended effect. It will definitely get fixed. My first foray was to just see what happened when returning an entity from a web service method.
<WebMethod()> _
 Public Function GetSalesOrder(ByVal orderNumber As String) As AWModel.SalesOrderHeader
   Dim aw As New AWModel.AWEntities
   Dim order = (From so In aw.SalesOrderHeader Where so.SalesOrderNumber = orderNumber).First
   Return order
 End Function
The payload for this does not have an EntityKey in it:

But I still wanted to see about serializing the key, since I was told that I should be able to do that with the independent key. So digging back into the code, I went looking for the EntityKey. I can see it in debug ,

but I couldn’t get at it in code.

This is where I got a look at the IEntitywithKey interface. This interface ONLY exposes the EntityKey.

So now I can get at the EntityKey and can even pull the two together:

However, even if I modified the method so that it returns an EntityKey, there’s a problem problem generating the WSDL and the proxy. Again, not the planned effect, but hopefully a bug.

So I will set this aside for now. (Darn)

There’s still much to look at here including the BinarySerialization.

My biggest interest in serializing entities if for writing multi-tiered applications where entities need to cross machine boundaries and will likely have update conflicts to contend with. I’m personally most interested in Web Services & WCF as this is how I write my smart client applications.

Since we can attach externally created entities to an ObjectContext, this leads to using services to capture entities coming in from a client app and the doing DML operations (update, insert, delete). Attach requires an Entity that implements IEntitywithKey, but AttachTo does not. Nevertheless, when it comes to Updates, the biggest conundrum will be dealing with concurrency and persisting original values somewhere. This is where the EntityKey will be a benefit. We won’t have to go looking for the matching entity, the object service should do that for us.

LINQ to SQL has an override for Attach that allows passing in the original entity and the existing entity, so that it’s own SaveChanges method will be able to determine the modified state of each property. Entity Framework does not have this yet, so finding the most efficient way to handle this is yet to come.

But hey, it’s a holiday weekend and I’ll just have to leave this for another time.= because the sun just came out.