ObjectContext.Add, ObjectContext.Delete

With Northwind, we have an ObjectQuery<Category> property on the context, an AddToCategorySet method and a DeleteOject method.

But it isn’t very intuitive. Indeed, it should be better to have a method Add and a method Delete on the ObjectQuery class.

To do this, I define two extension methods:

public static class ObjectQueryExtension

{

    public static void Add<T>(this ObjectQuery<T> objectQuery, T entity) where T : EntityObject

    {

        objectQuery.Context.AddObject(entity.EntitySetName(objectQuery.Context), entity);

    }

 

    public static void Delete<T>(this ObjectQuery<T> objectQuery, T entity) where T : EntityObject

    {

        objectQuery.Context.DeleteObject(entity);

    }

 

    private static string EntitySetName(this EntityObject entity, ObjectContext context)

    {

        if (entity.EntityKey != null)

            return entity.EntityKey.EntitySetName;

        return context.MetadataWorkspace.GetItemCollection(DataSpace.CSpace).OfType<EntityContainer>().First().BaseEntitySets.First(es =>

        {

            var entityTypeMetadata = context.MetadataWorkspace.GetItemCollection(DataSpace.CSpace).OfType<EdmType>().First(ese => ese.Name == entity.GetType().Name);

            while (entityTypeMetadata.BaseType != null)

                entityTypeMetadata = entityTypeMetadata.BaseType;

            return es.ElementType == entityTypeMetadata;

        }).Name;

    }

}

This entry was posted in 7671, 7674. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>