gpt4 book ai didi

c# - Entity Framework 4.0 - 使用泛型和反射按 ID 获取

转载 作者:行者123 更新时间:2023-11-30 17:21:31 25 4
gpt4 key购买 nike

我希望能够使用泛型和属性反射按 ID 加载实体,但不确定如何使用 Entity Framework 4.0 完成此任务。

我的抽象方法中有一个这样的方法:

public abstract T GetById(object id, TestContext context);

目前,因为它是抽象的,所以我必须在我创建的每个存储库类中实现这个方法:

public override TestObject GetById(object id, TestContext context)
{
return context.TestObject.First(x => x.TestId == (int) id);
}

有没有办法在我的抽象类中使用反射和泛型来完成同样的任务?

最佳答案

这是我使用的 VB 示例。我的 key 都是 GUID,但您可能会对此进行调整。

Public Shared Function GetKeyPropertyName(ByVal typeName As String) As String
Dim props = Type.GetType(typeName).GetProperties
For Each prop In props
Dim atts = prop.GetCustomAttributes(True)
For Each att In atts
If TypeOf (att) Is EdmScalarPropertyAttribute Then
If DirectCast(att, EdmScalarPropertyAttribute).EntityKeyProperty Then
Return prop.Name
End If
End If
Next
Next
Throw New ApplicationException(String.Format("No key property found for type '{0}'.", typeName))
End Function

Public Shared Function GetObjectById(Of T As EntityObject)(ByVal id As Guid) As T
Dim ctx = MyContext
Dim entityType As Type = GetType(T)
Dim entityTypeName As String = entityType.ToString
Dim keyProperty As String = GetKeyPropertyName(entityTypeName)

Dim container = ctx.MetadataWorkspace.GetEntityContainer(ctx.DefaultContainerName, Metadata.Edm.DataSpace.CSpace)

Dim entitySetName As String = (From meta In container.BaseEntitySets Where meta.ElementType.FullName = entityTypeName Select meta.Name).First()
Dim entitySetFullName As String = String.Format("{0}.{1}", container.Name, entitySetName)


Dim entityKeyValues As IEnumerable(Of KeyValuePair(Of String, Object)) = _
New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)(keyProperty, id)}

Dim key As New EntityKey(entitySetFullName, entityKeyValues)
Return DirectCast(ctx.GetObjectByKey(key), T)
End Function

关于c# - Entity Framework 4.0 - 使用泛型和反射按 ID 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3356573/

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