Dealing with foreign key with ADO.NET Entity Framework and Linq-to-Entities

by Pascal Parent 23. August 2009 13:24

We all know by now that table foreign keys are not directly accessible in Entity Framework and that searching on the subject on Google or Bing brings confusion and despair, at least it did to me. MSDN was not better, so I decided to go the trial and error route instead and I was not sorry.

I have found that, as with the .NET Framework, Linq often has a 1 liner solution to a problem, so my attitude was simple: find it. And so I did.

The trick is resolved with a simple and non-obscured object and it looks like this:

Entity.Reference.EntityKey = new EntityKey("Entities.Entity", "ReferencedColumn", "Value"));

Oddly enough, and contrary to what I have read, this command works for inserting, editing and deleting the foreign key. There are some caveats though, if you want to be able to delete the key, you’ll have to have the field / property nullabe in both the database and object.

Here is how I typically handle an insert, edit, delete situation:

 

private void Save(int ID)
        {
            try
            {

                int _id = Convert.ToInt32(ID);

                using (ObjectEntities db = new ObjectEntities())
                {
                    //Add a new object
                    if (_id == 0)
                    {
                        var _object = new object();

                        _object.Name = this.txtName.Text.Trim();

                        if (String.IsNullOrEmpty(this.SomeDropDown.SelectedItem.Value) == false)
                        {
                            _object.EntityReference.EntityKey = new 
EntityKey("ObjectEntities.Entity", "ID", Convert.ToInt32(this.SomeDropDown.SelectedItem.Value)); } else { _object.EntityReference.EntityKey = null; ; } //Some additional variable assignement db.AddToEntity(_object); db.SaveChanges(); // Rebuild the Grid // return to the list } else //Edit the object { var _object = ((from Item in db.Entity where Item.ID == _id select Item) .FirstOrDefault()); _object.Name = this.txtName.Text.Trim(); if (String.IsNullOrEmpty(this.SomeDropDown.SelectedItem.Value) == false) { _object.EntityReference.EntityKey = new
EntityKey("ObjectEntities.Entity", "ID", Convert.ToInt32(this.SomeDropDown.SelectedItem.Value)); } else { _object.EntityReference.EntityKey = null; ; } db.SaveChanges(); // Reload the current item with the changes } } // Do some logging } catch (Exception ex) { //Output some message about the error. } }

And that is all the is to it.

Related Links:

http://msdn.microsoft.com/en-us/library/dd283138.aspx 

http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.ientitywithkey.entitykey.aspx

Tags: , ,

General

The database dilemma

by Pascal Parent 2. January 2009 21:01

In a hosted environment the choice of databases is obvious, either Microsoft SQL or MySQL. However, there are other possibilities to store data such as XML, Microsoft Access and why exclude SQL Lite. All of these should work fine in a shared host environment which is my target. In fact for testing purposed I have hosting at GoDaddy.com, if it does not work there it’s back to the drawing board. The URL will be www.projectbanana.net, not that there is anything there yet.

So we are spoiled for choice in the database realm, I will pick the following:

  • Microsoft SQL 2005, 2008 and Express even tough i have not heard of a hosting company using express it help during development.
  • MySQL 4 and 5
  • SQL Lite

Initially, I will only focus on Microsoft SQL 2005 Express keeping in mind the other two. The next question becomes how to access the databases? The fact is that I do not want to have to write different providers for different databases. The possible and first choice is an ORM, luckily for us Microsoft gives us the ADO.NET Entity Framework, however GoDaddy does not run version 3.5 SP1 yet. So maybe an alternative would be more viable, the ALT.NET community gives us NHibernate for .NET but NHibernate is not Linq enabled yet. For that matter, one could say that there are some issues with the ADO.NET Entity Framework too, the .NET connector for MySQL is not EF ready yet either and all there is to reassure us that it will happen is this entry  by Reggie Burnett in May 2008 and then this one here. But the pressure is building and I expect it to come soon enough. The bottom line is that I cannot wait for either of these to happen. So ADO.NET Entity Framework it will be and if I shoot my self in the foot, I will have to rewrite the entire Data Access Layer. I wander about Subsonic though, they support SQL Server 2000 or 2005, MySQL, or Oracle with SQLLite, SQLCE, and PostGres coming soon according to their page not to mention Linq in the soon to come version 3. So I may have been hasty on my decision, watch for an update.

The good news is that SQL Lite’s ADO.NET provider supports ADO.NET Entity Framework, one less worry. What about other databases such as Oracle, Sybase and others? They do not seem too concerned about EF and they will tell you that there are 3rd party ADO.NET providers available. As for ORMs here is a list I found.

Next a short discussion on standards, components and patterns.

Tags: ,

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010 The ASP.NET Guy