views:

1096

answers:

3

I am getting an error while using the Entity Framework and C#.

I am trying to save any generic Entity with a line of code similar to the following:

objectContextInstance.AddObject(objectToSave.GetType().ToString(), objectToSave)

The error message I receive is:

The provided EntitySet name must be qualified by the EntityContainer name, such as 'EntityContainerName.EntitySetName', or the DefaultContainerName property must be set for the ObjectContext.

I do not understand this error because I have checked the Entity Data Model and verified that the DefaultContainerName has been set.

Can anyone provide any suggestions on how to troubleshoot this?

+1  A: 

Try this:

objectContextInstance.AddObject(objectToSave.GetType().Name, objectToSave)

Type.ToString() returns the namespace-qualified name, which is probably not also the name of the EntitySet.

Also, of course, this will only work if the entity type name and EntitySet name are the same. If you can't guarantee this, you could use reflection to examine the public methods of your object context for a signature that starts with AddTo and which takes a single parameter of the same type as objectToSave. (These methods are generated by the EDMX code generator and match entity types to entity sets.)

Of course, that would be a bit slow--but if yours isn't an insert-heavy database, that probably won't matter.

Ben M
That worked, thanks! What I don't understand is that I've used my strategy before on a WPF application and it passed my unit tests. However, now I am using it with ASP.NET MVC and it did not work. Anyway, thanks for the solution.
YeahStu
This is NOT guaranteed to work. The Typename, can easily not be the EntitySet name, which is what required. Craig's answer is correct.
Alex James
I put the caveat in there, and suggested a workaround if that's a problem. What more do you want?
Ben M
+1  A: 

Either wait for .NET 4.0 or use this workaround in the meantime.

Craig Stuntz
A: 

I found an extension method that gets me the EntitySetBase of the specified entity. This is what I am using to derive my EntitySetBase. I am using self tracking entities. So I have put this function into the .tt file in the extensions section:

  public static EntitySetBase GetEntitySet(this ObjectContext context, Type entityType)
  {
   if (context == null)
   {
    throw new ArgumentNullException("context");
   }

   if (entityType == null)
   {
    throw new ArgumentNullException("entityType");
   }

   EntityContainer container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);

   if (container == null)
   {
    return null;
   }

   EntitySetBase entitySet = container.BaseEntitySets.Where(item => item.ElementType.Name.Equals(entityType.Name))
                .FirstOrDefault();

   return entitySet;
  }

The client code goes like this:

string entitySetName = Context.GetEntitySet(user.GetType()).Name;

Hope this helps.

Nilotpal Das