gpt4 book ai didi

c# - 如何在附加到 DBContext 之前单独通过属性检索 EF 4 代码优先实体的 [Key]?

转载 作者:太空狗 更新时间:2023-10-29 22:27:50 27 4
gpt4 key购买 nike

给定 Entity Framework 4.0 代码优先实体

public class MyEntity
{
[Key]
public int MyEntityId { get; set; }
}

有没有办法在不知道属性名称的情况下检索用 [Key] 属性装饰的属性的值?

public class KeyReader<TEntity> : where TEntity : class
{
public int GetKeyValue(TEntity entity){
//get key value for entity
}
}

更新

我有一个 DBContext,所以我可以使用下面的代码:

var objectContext = ((IObjectContextAdapter) myContext).ObjectContext;
objectContext.ObjectStateManager.GetObjectStateEntry(entity).EntityKey.EntityKeyValues;

但是,这仅在实体已添加或附加到 DBContext 后才有效。问题是我想使用键及其值的动态知识来确定是否应执行插入或更新,从而确定是否将其添加或附加到上下文。当此代码成为可能时,为时已晚。

我已经编辑了问题标题以反射(reflect)这一点。

还有什么想法吗?

最佳答案

另一种可能的解决方案是使用反射来查找用 [Key] 属性装饰的属性并返回其值:

private object GetKeyValue<T>(T entity) where T : class
{
PropertyInfo key =
typeof(T)
.GetProperties()
.FirstOrDefault(p => p.GetCustomAttributes(typeof(KeyAttribute), true).Length != 0);

return key != null ? key.GetValue(entity, null) : null;
}

MyEntity instanceOfMyEntity = new MyEntity { MyEntityId = 999; };
object keyValue = GetKeyValue<MyEntity>(instanceOfMyEntity); // keyValue == 999

请注意,此方法只会返回第一个用 KeyAttribute 修饰的属性的值,如果找不到 Key 属性,则返回 null。

关于c# - 如何在附加到 DBContext 之前单独通过属性检索 EF 4 代码优先实体的 [Key]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9284055/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com