Fixing LINQ Error: Sequence contains no elements

When you get theLINQ Error “Sequence contains no elements”, this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault().


 Take for example the following code that uses First() on the results of the LINQ query. If there are no results, the call to First() triggers the “Sequenc contains no elements” error.:


var rel = (from r in relEnds
   where r.Contains(added.OtherEndKey(entity.EntityKey))
   select r).OfType<EntityReference>().First();


To fix the problem, all you have to do is change First() to FirstOrDefault() which returns a null value when there are no results from the select:

var rel = (from r in relEnds
   where r.Contains(added.OtherEndKey(entity.EntityKey))
   select r).OfType<EntityReference>().FirstOrDefault();


Kevin McNeish
INETA Speaker
.NET MVP 2002-2009
Chief Architect MM .NET Application Framework
www.oakleafsd.com

Entity Framework: Fixing "The number of errors in the conceptual type…does not match with the number of members on the object side type…"

You will typically get the error “The number of errors in the conceptual type…does not match with the number of members on the object side type” in version 1.0 of the Entity Framework when you have manually edited one or more of your entities. In version 1.0 of EF, all members of your conceptual model must be mapped to properties in your object model and all properties in  your entity classes adorned with the EdmScalarProperty attribute must be defined in your conceptual model.


Best Regards,
Kevin McNeish
INETA Speaker
.NET MVP 2002-2009
Chief Architect, MM .NET Application Framework
www.oakleafsd.com

Entity Framework: Programmatically determining the Entity Set name of an Entity

Here is an extension method for the Object Context that allows you to programmatically derive an Entity Set name associated with a particular entity. To put this in context, when adding a new entity object to an Object Context, you need to specify the associated entity set of the entity you are adding.


Here is an extension method for the ObjectContext class that allows you to do this:


public static string GetEntitySetFullName(this ObjectContext, EntityObject entity)
{
   // If the EntityKey exists, simply get the Entity Set name from the key

   if (entity.EntitKey != null)
   {
      return entity.EntityKey.EntitySetName;
   }
   else
   {
      string entityTypeName = entity.GetType().Name;
      var container = context.MetaDataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
      string entitySetName = (from meta in container.BaseEntitySets
                              where meta.ElementType.Name == entityTypeName
                              select meta.Name).First();

      return container.Name + “.” entitySetName;

   }
}


Best Regards,
Kevin McNeish
.NET MVP 2002-2009
Chief Architect MM .NET Application Framework
INETA Speaker
www.oakleafsd.com

Understanding the Entity Framework ConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows…

When working with the Entity Framework in n-Tier applications where you are unattaching and attaching entities from an object context, you may encounter this exception:


Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.


This exception is letting you know that no rows were updated. There are several reasons why you may encounter this error.


One simple reason is that when attaching entities to an Object Context, you need to use the AddObject() method if the entity is newly created (and doesn’t have an Entity Key), whereas you can use the Object Context Attach() method if the entity already exists and is being updated. Here is some code to demonstrate this (where “EntityContainerName” is the name of your Entity Framework container and “EntitySetName” is the name of the Entity Set to which you are adding the entity):


if (entity.EntityKey == null || entity.EntityKey.IsTemporary)
{
   this.ObjectContext.AddObject(“EntityContainerName.EntitySetName”, entity);
}
else
{
   this.ObjectContext.Attach(entity);
}


Note that you need to be careful when adding entities that are related to other entity objects because Object Services attempts to add the related objects too.


Best Regards,
Kevin McNeish
.NET MVP 2002-2009
Chief Architect, MM .NET Application Framework
INETA Speaker
www.oakleafsd.com

Using Reflection to Determine if a Property Data Type is Nullable

You can easily determine if the data type of an object property is nullable using the following code:


Type t = objectReference.GetType();
Type pt;

// Test for Nullable
bool isNullable = pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
PropertyInfo pi = t.GetProperty(“MyPropertyName”);

if (isNullable)
{
   // Returns the basic data type without reference to Nullable (for example, System.Int32)
   pt = pi.PropertyType.GetGenericArguments()[0];
}


Best Regards,
Kevin McNeish
Chief Architect, MM .NET Application Framework
INETA Speaker
.NET MVP 2002-2009
www.oakleafsd.com