How to retrieve entity keys without materializaing entities?

醉酒当歌 提交于 2019-12-11 03:31:30

问题


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?


回答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.



来源:https://stackoverflow.com/questions/18064064/how-to-retrieve-entity-keys-without-materializaing-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!