2
我需要的是這樣的:如何檢索沒有實體化實體的實體鍵?
context.EntitiesDbSet.Keys.Where(predicate);
這裏謂詞類型Expression<Func<Entity,bool>>
的,我知道,現在唯一的解決辦法是使用通過metada分析產生的投影。 有沒有更簡單的方法?
我需要的是這樣的:如何檢索沒有實體化實體的實體鍵?
context.EntitiesDbSet.Keys.Where(predicate);
這裏謂詞類型Expression<Func<Entity,bool>>
的,我知道,現在唯一的解決辦法是使用通過metada分析產生的投影。 有沒有更簡單的方法?
我知道的一種方式是通過反射,在實體上使用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);
}
}
}
}
我相信會有所幫助。
預測有什麼問題? –
@WiktorZychla沒有錯,但需要生成用於實例化EntityKey的表達式。當然,如果我手動編碼,我可以使用Selec(e => e.Id)。但在這種情況下,我知道PK只是名稱爲Id的一列。 –