December 2008 - Posts

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;

    }

}

Posted by Matthieu MEZIL | with no comments

Zeeshan Hirani christmas present

Zeeshan is a great EF community contributor with his blog and, since a short time ago, he also answers a lot in msdn forum.

I take advantage of this post to tell you that the msdn forum url will change this week.

Zeeshan makes us a very usefull christmas present with a big article about EF (514 pages !!!) and also the code of the article.