【问题标题】:How to retrieve entity keys without materializaing entities?如何在不实现实体的情况下检索实体键?
【发布时间】:2013-08-05 17:28:11
【问题描述】:

我需要这样的东西:

context.EntitiesDbSet.Keys.Where(predicate);

这里的谓词类型为Expression<Func<Entity,bool>> 我现在知道的唯一解决方案是使用通过元数据分析生成的预测。 有没有更简单的方法?

【问题讨论】:

  • 投影有什么问题?
  • @WiktorZychla 没有错,但需要生成用于实例化 EntityKey 的表达式。当然,如果我手动编码,我可以使用 Selec(e => e.Id)。但在这种情况下,我知道 PK 正是一列名称为 Id。

标签: .net entity-framework entity-framework-5


【解决方案1】:

我知道的一种方法是通过反射,在实体上使用 KeyAttribute 并在实体上搜索带有 KeyAttribute 的属性。示例:

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);
            }
        }
    }
}

我相信这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2016-05-19
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多