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

标签 c# .net entity-framework reflection

我希望能够使用泛型和属性反射按 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/

相关文章:

c# - 删除文件夹的内容而不是文件夹本身?

c# - 如何从P和Q计算出RSA的附加私钥参数?

c# - LINQ语法问题

c# - 如何通过 Entity Framework 访问多对多表?网站

c# - 从 JSON 编码的二进制数据恢复图像

asp.net - 查找 .NET 解决方案中未使用的资源 (.resx)

asp.net - 我可以使用 owin 和 oauth 提供商的 asp.net 成员(member)资格吗?

entity-framework - 无法在 ASP.NET Core 项目中安装 Microsoft.EntityFrameworkCore

c# - Entity Framework : An object with the same key already exists in the objectstatemanager

c# - Enterprise Architect 模型搜索 XML 格式