Click here to Skip to main content
15,887,596 members
Articles / Programming Languages / C#
Tip/Trick

Get an Entity Framework Object anyway

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
4 Feb 2012CPOL 23.4K   5   6
How to get an Entity Framework object - either from ObjectContext, from database or from scratch
In Entity Framework, you can get an Object from the ObjectContext[^] using GetObjectByKey[^] or TryGetObjectByKey[^]. When the object is not yet loaded into the ObjectContext, Entity Framework tries to get it from the database. But what if it doesn't even exist there? Take this:

C#
public static TEntity GetObjectAnyway<TEntity>(this ObjectSet<TEntity> os, params object[] primaryKeyValues) where TEntity : EntityObject, new()
{
    object oEntity;
    TEntity entity;
    var ek = os.CreateEntityKey(primaryKeyValues);
    if (os.Context.TryGetObjectByKey(ek, out oEntity))
        entity = (TEntity)oEntity;
    else
    {
        entity = new TEntity { EntityKey = ek };
        foreach (var v in ek.EntityKeyValues)
        {
            typeof(TEntity).InvokeMember(v.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty, null, entity, new[] { v.Value });
        }
        os.AddObject(entity);
    }
    return entity;
}


You'll need some helpers to make it work, here's the whole code:
C#
using System.Data;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Reflection;
using System.Data.Metadata.Edm;

namespace MyNamespace
{
    public static class Extensions
    {
        public static EntityKey CreateEntityKey(this EntitySet es, params object[] primaryKeyValues)
        {
            var s = string.Format("{0}.{1}", es.EntityContainer.Name, es.Name);
            var ien = primaryKeyValues.Select((o, i) => new EntityKeyMember(es.ElementType.KeyMembers[i].Name, o));
            return new EntityKey(s, ien);
        }

        public static EntityKey CreateEntityKey<TEntity>(this ObjectSet<TEntity> os, params object[] primaryKeyValues) where TEntity : class
        {
            return os.EntitySet.CreateEntityKey(primaryKeyValues);
        }

        /// <summary>
        /// Returns an object that has the specified primary key values from database or <see cref="ObjectContext"/>, even if it wasn't already existing.
        /// </summary>
        /// <remarks>
        /// This method makes the following attempts, until it is able to return the object wanted.
        /// <list type="number">
        /// <item><description>
        /// Try to get the object from the <see cref="ObjectContext"/>.
        /// </description></item>
        /// <item><description>
        /// Try to get the object from the database.
        /// </description></item>
        /// <item><description>
        /// Create a new object having the given <paramref name="primaryKeyValues"/>.
        /// </description></item>
        /// </list>
        /// </remarks>
        /// <typeparam name="TEntity">The type of the wanted object.</typeparam>
        /// <param name="os">The <see cref="ObjectSet{T}"/> where the wanted object belongs to.</param>
        /// <param name="primaryKeyValues">The values of the object's primary key in the order defined by the primary key.</param>
        /// <returns>The object wanted.</returns>
        public static TEntity GetObjectAnyway<TEntity>(this ObjectSet<TEntity> os, params object[] primaryKeyValues) where TEntity : EntityObject, new()
        {
            object oEntity;
            TEntity entity;
            var ek = os.CreateEntityKey(primaryKeyValues);
            if (os.Context.TryGetObjectByKey(ek, out oEntity))
                entity = (TEntity)oEntity;
            else
            {
                entity = new TEntity { EntityKey = ek };
                foreach (var v in ek.EntityKeyValues)
                {
                    typeof(TEntity).InvokeMember(v.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty, null, entity, new[] { v.Value });
                }
                os.AddObject(entity);
            }
            return entity;
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 2 Pin
Jark10-Jul-13 2:05
Jark10-Jul-13 2:05 
GeneralRe: Good question. Try to post it in the C# forum (<a href="http... Pin
Harry von Borstel7-Feb-12 21:24
Harry von Borstel7-Feb-12 21:24 
GeneralHI. I want know that how i can make a polygan and move it on... Pin
Member 86251607-Feb-12 6:50
Member 86251607-Feb-12 6:50 
GeneralRe: HI. I want know that how i can make a polygan and move it on... Pin
Member 86251607-Feb-12 6:51
Member 86251607-Feb-12 6:51 
GeneralRe: Please don't attempt to hijack another thread/article. You d... Pin
Pete O'Hanlon8-Feb-12 1:12
mvePete O'Hanlon8-Feb-12 1:12 
GeneralReason for my vote of 5 good article for understanding EF on... Pin
Nikhil_S7-Feb-12 0:00
professionalNikhil_S7-Feb-12 0:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.