All posts by Julie

Vermont IT Jobs: Part-time FoxPro development gig in Burlington through July

From Seven Days Classifieds:

Temporary position on breast cancer research project (http://www.uvm.edu/~vbcss). FoxPro for Windows knowledge and experience is required. Half to full-time through July. Strong teamwork skills needed. Flexible hours. Salary commensurate with skills and experience.

Send resume and cover letter to Dawn.Pelkey@uvm.edu.

The University of Vermont is an Equal Opportunity/Affirmative Action Employer. Applications from women and people from diverse racial, ethnic, and cultural backgrounds are encouraged.

Entity Framework Lazy Loading by Context or by Property?

When Entity Framework finally brought in support for Lazy Loading, there were still complaints. The lazy loading in EF4 is context based, not property based as defined by some of the other ORMs. (I’m not sure which ones or how many.)

I was thinking about this today and realized that EF does, in fact, support property level lazy loading.

There are three essential types of entities in EF4 –

  1. EntityObjects
  2. POCOs that lean on dynamic proxies at runtime
  3. POCOs that depend on EF’s snapshot notification

The POCOs that use dynamic proxies can do so only when every single property is marked virtual. Then they benefit from the same notification behavior at runtime as do EntityObjects and they benefit from lazy loading.

Simple POCOs that do not use dynamic proxies can still benefit from lazy loading. As long as the relationship property is marked virtual and additionally, properties that point to collections have to be a collection type that implements ICollection, the property will be loaded on demand (when the context’s lazy loading is enabled).

In this last case (the simple POCOs), you can pick and choose which of the relationship properties are able to lazy load. Then with the context set to LazyLoadingEnabled=true, lazy loading will occur, but only for the properties you have specified.

Now, I’m not sure how this compares to those other ORMs whose users criticized the context-level lazy loading, but it feels like it might be a lot closer then they realized. And I’m absolutely interested in finding out if I’m on the right track or completely off base (in which case I can only ask: “be gentle” 🙂 ).

Small Change in EF Loading Behavior from VS2008

In the process of updating my book, I have to recheck every statement and every line of code. A lot has changed. It’s as though I were writing the whole thing from scratch.

Here’s a small but notable change that I found.

In .NET 3.5 you cannot Load an EntityReference for an Added entity even when the entity has the critical piece of information — the EntityReference.EntityKey of the item to be loaded. It will fail with an exception.

In .NET 4, it works. You can set the foreign key property or the EntityReference.EntityKey and then load that related entity either explicitly or via lazy loading.

I’m pretty sure this is a result of the improvements made to the query generation. .NET 3.5 had a convoluted way of loading entity reference data. Now it’s more straightforward. However, I have only tested it with FKs.

Defining Constraints in an EF4 model that don’t exist in the database

In the first version of Entity Framework, if you wanted to create a PK/FK association between entities where there was no such constraint defined in the database you have to manually edit the SSDL (and lose that edit if you update the model from db).

Why would you want to do this? The typical use case is when you are stuck with a database that is poorly designed and you are not allowed to make changes to it.

In Entity Framework 4, as long as the Primary Keys are defined in the db (otherwise the entities are read only like views, although you can map stored procs to them and make them updatable) and you have foreign keys in the model, you can define the constraint easily.

Here’s a dependent table. It does have a foreign key property (with a typo :)) but notice under indexes there is no PK_FK defined pointing back to the table which PrimartyID(sic) refers to.

 

noconstraint

 

When I pull this table and PrimaryTable into the model there is no association between them.

I create an association:

noconstraint2

and then define the constraint in the model. You need to open the properties window of the association and then click on the Referential Constraint ellipses

noconstraint2a

to get to the ref constraint dialog:

noconstraint3

This is a new feature that comes with foreign key associations. You can’t do this if you do not include foreign key ids in your model.

Now for the test:

  private static void fakePKFK()
    {
      var context = new manytomanytestEntities();
      var list = context.PrimaryTables.Include("DependentTables").ToList();
      var firstPrimary = list[0];
      var newDependant = new DependentTable {DependentName = "ChildNew for FIrst"};
      firstPrimary.DependentTables.Add(newDependant);
      context.SaveChanges();
    }

And it works. THe query returns graphs of primary & dependents. The SaveChanges inserts a new dependent. Rerunning the code brings me back the new dependent in the primary’s collection.

Have not tested *:*. Someone has already asked me about code only. I don’t know. But feel free to take the time to test it out and let me know! 🙂

Entity Framework ObjectContext and Reporting

I had an email this morning from someone who was having trouble with reports populated using Entity Framework.

He was running a report repeatedly but changing the filter.

For example, Customers whose last name is Smith, then Customers whose last name is Barber.

The problem was that after running the Smith report, the Smiths were showing up on the Barber report.

The problem is that he was using one context to generate both reports.

The context just keeps collecting all of the entities you feed into it. More accurately, the context keeps collecting ObjectStateEntries (which manage the state for an instantiated entity and act as pointers back to the entity objects in memory) for all of the entities you feed to it.

Best to just have a context that exists only for the life time of the method which gets the report data.

Public List<Customer> GetCustomers(string lastname)
{
   using (var context=new MyEntities()) 
  {
     return context.Customers.Where(c=>c.LastName==lastname).ToList();
  }
} 

Now you don’t have to worry about cached entities. 

This is not a hard rule but a guideline. For example, one exception would be when you are drilling in to reports.

Yes you can read (and probably write) Spatial Data with Entity Framework

After thinking about the issue with EF4 still not supporting spatial data, I emailed spatial data wizard, Jason Follas, and asked him his thoughts. He’s not too familiar with EF but said if EF supported blob types then you could just use the Microsoft.SqlServer.SqlGeometry type to read in the blob data from a stream.

I emailed back and said, well then if there’s a way to cast the geometry data, then we can create a view to provide the spatial data and stored procs to update it.

Then he and I both ended up with the same solution.

He created a table from scratch. I downloaded a sample table from CodePlex that has US Census Data containing in a SQL Server 2008 table that contains a geometry column.

Then we both came up with the correct cast (I floundered but let the error messages and some googling (oh wait, I think I was Binging :)) help me figure out what I was supposed to cast to) and the following view was born.

SELECT     StateID, StateName, CONVERT([varbinary](MAX), geom, 0) AS Geo
FROM         dbo.State

Well, it was born twice. One twin in Vermont, the other in Ohio. 🙂

EF’s EDM Wizard happily reads in the view:

state

And has no problem executing queries and materializing the object:

      using (var context=new myEntities())
      {
        var stateData = context.States.First();
        var geoProperty = stateData.geomBlob();
      }

Next is to take geoProperty and stream it into a SqlGeometry type (thanks again to Jason for pointing this out), and you are good to go.

If you want to do updates, then you’ll need some stored procs that you can pass the binary data into which will convert (on the server side) back into the geometry type. This is theoretical on my part. You should absolutely be able to do this. I just haven’t done it myself. Hopefully someone will try it out and let me know that it works! 🙂

And there’s no reason this shouldn’t work in both EF1 and EF4.

Querying is a different story. LINQ does not support querying the spatial data nor does ESQL. But EF supports query stored procedures if that can help. I really don’t know much about working with the spatial types so this perhaps Jason and I can continue to put our heads (and expertise) together on this.

I’m not working through part where we read in the SqlGeometry type because I don’t have the correct assembly on my computer. Jason has a blog post about getting the correct assembly for using the SqlGeometry type directly in .NET.

So, while the EDM doesn’t support the spatial types directly, it is still possible to work with them when using EF without too much inconvenience.

SQL Server 2008 Data Types and Entity Framework 4

Because I’ve had a lot of conversations about spatial data types lately, I thought I would create a SQL Server table that contained one of every type then bring it into an entity data model using the wizard to see what happens. This is in EF4.

Here are screenshots of the table and the entity showing their property types.

everydatatypetable

This way you can see what is and isn’t supported. The wizard excluded four fields it still doesn’t recognize at all.

  • geography
  • geometry
  • hierarchyid
  • sql_variant

If you focus on the entity, you can compare the property names to the property types to see how different data types are treated. E.g. the xml property is a String and the real property is a Single.

The fields that use Max become properties whose Max Length property =”Max”

Entity Framework Graphs, Detaching and Lazy Loading

If you have a graph of entities which are being managed by an ObjectContext, e.g, a LineItem and its Product, and for one reason or another, you detach the Product from the context, lazy loading will query for that Product again if you happen to call LineItem.Product. Now you will have two instances of that product in memory and one of them is being change-tracked.

It’s understandable behavior, but I know that someone will get bitten by this someday.

It’s more likely to happen when you are exploring how relationships work and doing weird things like I do. But it’s also possible that you might do it in a production app as well if you don’t know what you’re doing.

Vermont IT Jobs: .NET Developer in MIddlebury

I worked with the small development team at this company a few years ago as a mentor and it is a great work environment. Super nice folks. Company has a deep Vermont history and you get to be in Middlebury.

Co-Operative Insurance (http://www.co-opinsurance.com/)

We are currently seeking a new addition to our .NET development team. Applicants should have a strong technical background as well as excellent communication and interpersonal skills. Additionally, applicants should possess the ability to creatively solve problems in a sound, efficient manner. As a member of our .NET team, you will be expected to write neat, efficient code containing in-line documentation. Furthermore, developers are expected to fully test and document their work for the end user.

Qualified candidates must have experience with the following technologies: VB.Net, Visual Studio, SQL, ASP.NET, HTML/XHTML/DHTML/JavaScript/AJAX and Source Control Software. Experience with the following would be a plus: Java, XSL, Subversion, and Cruise Control.

This full-time position comes with a great benefits package, a friendly, professional work environment, and an emphasis on personal-professional life balance. Our high retention levels back up those claims. Based in Middlebury, Co-operative Insurance Companies provides financial security to home, auto, farm and small business owners across VT and NH. Our 70 employees are dedicated to offering top-notch service to our Co-op members.

Interested candidates should send a resume and cover letter (no later than 2/26/2010) as follows:

jobs@ciui.net

or

Human Resources

Co-operative Insurance Companies

PO Box 5890

Middlebury, VT 05753

Beware Self-Tracking Entities Conflict with Entity Framework CTP & VS2010 RC

Adding a note to highlight Damien’s comment below. Damien is on the EF team and does not recommend using the current Feature CTP with the RC. A new version will be available "soon".

In comments of another blog post Ivan reminds me of something else I ran into the the VS2010 RC.

I tweeted on Tuesday that the Self-Tracking Entities template is now “in the box”.

I also blogged on Tuesday about a change to a file, EF.Utility.CS.ttinclude (or EF.Utility.VB.ttinclude) which the EF T4 Templates depends. The RC version is different from the Beta 2 version.. Using the Beta 2 EF POCO Template with VS2010 RC

The EF Feature CTP contains Code Only functionality and an earlier version of the STE template. Like the POCO template, that STE template depends on the Beta 2  version of the ttinclude file. But the STE template in the VS2010 RC depends on the newer version of the ttinclude file.

If you install the EF Feature CTP on top of the VS2010 RC, you will overwrite the Self Tracking Entities template with the old version and it will no longer work.

I tried to outsmart the process by saving the Item Template zip files, installing the CTP and then copy the RC zip files over the ones which  the CTP installed. That didn’t work out very well.

Option 1

However, doing a repair on VS2010 RC after installing the Feature CTP (and in my case totally mucking things up trying to be clever with the zip files) let me have my cake (Code Only support that works with the VS2010 RC -yay) with the icing (the RC version of teh Self-Tracking Entities which got reinstalled during the repair).

Option 2

Another alternative is to run the STE template item before installing the CTP. The STE template item creates two template files, one for the context and the other for the entities. Only the entities template is impacted by the Feature CTP installation. Copy the contents of the entities template file somewhere. Then after installing the CTP, you’ll initially create the Beta 2 version of the entities template file, just copy the code from the new file into the template file that’s created.

Option 3
If you don’t need to use Code Only, don’t install the Feature CTP! 🙂 Originally, the Feature CTP was a source for Code Only support, STEs and the POCO template. The POCO template is now an extension (although see the above link for some current incompatibility issues with the RC) and STEs are now in the box.

Eventually these conflicts will all get sorted out.