我有一个模型
public class Application : BaseModel, IApplication
{
[Key]
public int ApplicationId { get; set; }
public DateTime? Date { get; set; }
public string ApplicationTypeId { get; set; }
public List<AlternateSigningAuthority> AlternateSigningAuthorities { get; set; }
public List<Land> Lands { get; set; }
}
还有一个模型
public class Land : BaseModel, IEquatable<Land>/*, ILand*/
{
[Key]
public int LandId { get; set; }
[ForeignKey("ApplicationId")]
public int ApplicationId { get; set; }
public int Unit { get; set; }
}
类似地,我有一个 AlternateSigningAuthority 模型。我想获得这些模型的主键。
我有适用于应用程序的代码
var type = typeof(Application);
var properties = type.GetProperties();
var property = properties
.FirstOrDefault(p => p.GetCustomAttributes(false)
.Any(a => a.GetType() == typeof(KeyAttribute)));
if (property != null)
{
string msg = "The Primary Key for the {0} class is the {1} property";
Console.WriteLine(msg, type.Name, property.Name);
}
一旦我添加
foreach (var prop in properties)
{
var attributes = property.GetCustomAttributes(false);
foreach (var attribute in attributes)
{
if (attribute.GetType() == typeof(KeyAttribute))
{
string msg = "The Primary Key for the {0} class is the {1} property";
Console.WriteLine(msg, type.Name, attribute.ToString());
}
}
我没有得到主键。我想使用应用程序模型来获取其他模型的 key 。
最佳答案
您只需要调用 Attribute.GetCustomAttribute
AddressViewModel viewModelInstance=new AddressViewModel();
PropertyInfo[] properties = viewModelInstance.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
var attribute = Attribute.GetCustomAttribute(property, typeof(KeyAttribute))
as KeyAttribute;
if (attribute != null) // This property has a KeyAttribute
{
// Do something, to read from the property:
object val = property.GetValue(viewModelInstance);
}
}
我引用了这个链接 Get [key] property from ViewModel
关于c# - 如何获取主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47098782/