0

I'm using Entity Framework version 1, and i'm trying to create a generic repository, but I can't find a way to get the Primary Key of each table. Has anyone solved this issue?

UPDATE: My target use for this would be for a generic method that looks like this:

TModel GetByPrimaryKey(Guid key)
{

}
Remus
  • 1,433
  • 3
  • 14
  • 24

2 Answers2

3

In the end, I adapted @Marc's answer from here: C# Linq-SQL: An UpdateByID method for the Repository Pattern

The result is something like this:

    public TModel GetByPrimaryKey(Guid key)
    {
        // get the row from the database using the meta-model
        MetaType meta = _DB.Mapping.GetTable(typeof(TModel)).RowType;
        if (meta.IdentityMembers.Count != 1) throw new InvalidOperationException("Composite identity not supported");
        string idName = meta.IdentityMembers[0].Member.Name;

        var param = Expression.Parameter(typeof(TModel), "row");
        var lambda = Expression.Lambda<Func<TModel, bool>>(
            Expression.Equal(
                Expression.PropertyOrField(param, idName),
                Expression.Constant(key, typeof(Guid))), param);

        return _DB.GetTable<TModel>().FirstOrDefault(lambda);
    }

...where _DB is a DataContext.

I hope this helps someone in the future.

Community
  • 1
  • 1
Remus
  • 1,433
  • 3
  • 14
  • 24
0

You have to use some kind of reflection.

Try something like this:

private PropertyInfo GetPrimaryKeyInfo<T>()
{
    PropertyInfo[] properties = typeof(T).GetProperties();
    foreach (PropertyInfo pI in properties)
    {
        System.Object[] attributes = pI.GetCustomAttributes(true);
        foreach (object attribute in attributes)
        {
            if (attribute is EdmScalarPropertyAttribute)
            {
                if ((attribute as EdmScalarPropertyAttribute).EntityKeyProperty == true)
                    return pI;
            }
            else if (attribute is ColumnAttribute)
            {

                if ((attribute as ColumnAttribute).IsPrimaryKey == true)
                    return pI;
            }
        }
    }
    return null;
}
RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • thanks - I should have been clearer from the beginning. My target is to use this information in a "getbyprimarykey" generic method. I've updated the question. – Remus Nov 23 '10 at 01:09
  • @Remus - check out this SO answer: http://stackoverflow.com/questions/2958921/entity-framework-4-how-to-find-the-primary-key/3046102#3046102 Not 100% sure if it will work with EF1 though. – RPM1984 Nov 23 '10 at 02:42
  • that helps. I noticed that the link you sent me uses an OjbectContext whereas I have a DataContext. Any hints on porting the solution to the VS generated Model that uses a DataContext? – Remus Nov 23 '10 at 16:42