Miles Gibson
Miles Gibson

Reputation: 45

Retrieve a record using T, when you don't know the primary key

I have a routine to get the primary key name for a given <T> entity. But I don't know the syntax for retrieving a record using this value.

For a given routine such as:

public virtual T GetRecord(int id) 
{
    string keyName = GetKey(T);

    // -------------- this is the part I don't know ---------------
    //
    return context.Entity<T>.Find(x => x.KeyName.Value == id);
    //
    //-------------------------------------------------------------
}

public virtual string GetKey(T entity)
{
    var entityType = context.Model.FindEntityType(typeof(T));
    var primaryKeyName = entityType.FindPrimaryKey().Properties.First().Name;
    var set = context.Set<T>();
    var orderedEntities = (set.OrderBy(e => e.GetType().GetProperty(primaryKeyName).GetValue(e, null))).ToList();
    string keyName = context.Model
                            .FindEntityType(typeof(T))
                            .FindPrimaryKey() 
                            .Properties
                            .Select(x => x.Name)
                            .Single();

    return keyName;
}

Upvotes: 0

Views: 58

Answers (1)

Plasmadog
Plasmadog

Reputation: 106

You don't need the key name. EF already knows what property to use as the primary key, so this should work:

context.Entry<T>.Find(id)

Upvotes: 4

Related Questions