如何根据注释 [key] 标记从 ASP NET MVC 模型对象中识别主键参数?

How identify a primary key parameter from an ASP NET MVC Model object based on annotation [key] tag?

鉴于此模型 class

public class MyClass
{
    [Key]
    public uint MyObjectId { get; set; }
    public long Param1 { get; set; }
    public string Param2 { get; set; }
}

如何根据[Key]注释以编程方式识别主键参数?

在这种情况下,它将是 MyObjectId

你可以使用反射。

public class MyClass
{
    [Key]
    public uint MyObjectId { get; set; }
    public long Param1 { get; set; }
    public string Param2 { get; set; }
}

void Main()
{
    var properties = typeof(MyClass).GetProperties()
      .Where(prop => prop.IsDefined(typeof(KeyAttribute), false));
}