Reputation: 4052
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?
Upvotes: 1
Views: 6557
Reputation: 595
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.
Upvotes: 0
Reputation: 126587
Either wait for .NET 4.0 or use this workaround in the meantime.
Upvotes: 2
Reputation: 22512
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.
Upvotes: 4