What is the name of the entity key for ObjectSetT>?

.net c# entity-framework

Question

I've developed a universalObjectSet<T> I keep a general repository here.

What I'd want to acquire is thename an of the EntityKeyObjectSet<T> so I may use it in theDataContext.GetObjectByKey .

I've looked everywhere and looked very carefully, but I can't seem to locate this value anywhere in theObjectSet class.

1
6
7/25/2010 6:44:32 AM

Accepted Answer

I spent some time looking for a decent approach to do this but was unable. To create Entity Keys for TryGetObjectByKey requests, I usually end up creating a GetEntityByKey extension method someplace. The main principle behind creating the entity key is as follows:

internal class Program
{
    private static void Main(string[] args)
    {
        var dc = new AdventureWorksLT2008Entities();
        object c;
        dc.TryGetObjectByKey(GetEntityKey(dc.Customers, 23), out c);
        var customer = c as Customer;
        Console.WriteLine(customer.EmailAddress);
    }

    private static EntityKey GetEntityKey<T>(ObjectSet<T> objectSet, object keyValue) where T : class
    {
        var entitySetName = objectSet.Context.DefaultContainerName + "." + objectSet.EntitySet.Name;
        var keyPropertyName = objectSet.EntitySet.ElementType.KeyMembers[0].ToString();
        var entityKey = new EntityKey(entitySetName, new[] {new EntityKeyMember(keyPropertyName, keyValue)});
        return entityKey;
    }
}

You may be able to do something comparable. For the sake of simplicity, this example only considers a single field per EntityKey; if you wanted to use several value keys, you would need to useObjectSet<T>.ElementType.KeyMembers then input the EntityKey constructor with all of your keys.

5
7/25/2010 7:55:57 AM

Popular Answer

Generic:

public class GenericoRepositorio<T> : IGenericoRepositorio<T> where T : class
{
    protected readonly ObjectSet<T> ObjetoSet;
    protected readonly ModeloContainer Contexto;

    public GenericoRepositorio(ModeloContainer contexto)
    {
        Contexto = contexto;
        ObjetoSet = Contexto.CreateObjectSet<T>();
    }

    public T Carregar(int id)
    {
        object objeto;
        Contexto.TryGetObjectByKey(GetEntityKey(ObjetoSet, id), out objeto);
        return (T)objeto;
    }

    private static EntityKey GetEntityKey<T>(ObjectSet<T> objectSet, object keyValue) where T : class
    {
        var entitySetName = objectSet.Context.DefaultContainerName + "." + objectSet.EntitySet.Name;
        var keyPropertyName = objectSet.EntitySet.ElementType.KeyMembers[0].ToString();
        var entityKey = new EntityKey(entitySetName, new[] { new EntityKeyMember(keyPropertyName, keyValue) });
        return entityKey;
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow