2

I need something like this:

context.EntitiesDbSet.Keys.Where(predicate);

And predicate here is of type Expression<Func<Entity,bool>> The only solution I know for now is to use projections generated via metada analysis. Are there any simpler methods?

Dan Drews
  • 1,966
  • 17
  • 38
Pavel Voronin
  • 13,503
  • 7
  • 71
  • 137
  • And what's wrong with projections? – Wiktor Zychla Aug 05 '13 at 19:37
  • @WiktorZychla Nothing wrong but requires generating expressions for instantiating EntityKey. Sure, if I code this manually I can use Selec( e => e.Id). But in this situation I know that PK is exactly one column with name Id. – Pavel Voronin Aug 05 '13 at 20:07

1 Answers1

1

One way I know is through reflection, using KeyAttribute on Entities and search on Entity the property with KeyAttribute. Example:

using System;
using System.ComponentModel.DataAnnotations;

namespace HelloWorld
{
    public class MyEntity
    {
        [Key]
        public int EntityID { get; set; }
        public string Name { get; set; }
    }

    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Type myType = typeof(MyEntity);

            var myProps = myType.GetProperties().ToList()
                .Where(prop => prop.GetCustomAttributes(true).Any(a => a is KeyAttribute));

            foreach (var element in myProps) {
                Console.WriteLine(element.Name);
            }
        }
    }
}

I believe that would help.

Julio Borges
  • 661
  • 14
  • 29