c# - Entity Framework 4 : How to find the primary key?

标签 c# .net entity-framework entity-framework-4 primary-key

我正在尝试使用 EF4 创建一个通用方法来查找对象的主键。

例子

public string GetPrimaryKey<T>()
{
    ...
}

为了提供更多信息,我正在使用 Tekpub StarterKit,下面是我正在尝试启动和运行的类(class)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.Data.Objects.ELinq;
using System.Data.Linq;
using Web.Infrastructure.Storage.EF4;

namespace Web.Infrastructure.Storage {
public class EFSession:ISession {
    PuzzleEntities _db;//This is an ObjectContext
    public EFSession() {
        _db = new PuzzleEntities();
    }

    public void CommitChanges() {
        _db.SaveChanges();
    }
    /// <summary>
    /// Gets the table provided by the type T and returns for querying
    /// </summary>
    private ObjectSet<T> GetObjectSet<T>() where T:class {
        return _db.CreateObjectSet<T>();
    }

    private T GetByPrimaryKey<T>() where T: class
    {
        .....
    }

    public void Delete<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T: class{

        foreach (T item in All<T>().Where(expression))
        {
            GetObjectSet<T>().DeleteObject(item);
        }
    }

    public void Delete<T>(T item) where T : class {
        GetObjectSet<T>().DeleteObject(item);
    }

    public void DeleteAll<T>() where T : class {
        foreach(T item in All<T>())
        {
            GetObjectSet<T>().DeleteObject(item);
        }
    }

    public void Dispose() {
        _db.Dispose();
    }

    public T Single<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T:class {
        return GetObjectSet<T>().SingleOrDefault(expression);
    }

    public IQueryable<T> All<T>() where T : class {
        return GetObjectSet<T>().AsQueryable();
    }

    public void Add<T>(T item) where T : class {
        GetObjectSet<T>().AddObject(item);
    }
    public void Add<T>(IEnumerable<T> items) where T : class {
        foreach (T item in items)
        {
            GetObjectSet<T>().AddObject(item);
        }
    }
    public void Update<T>(T item) where T : class {
        //nothing needed here
    }
}
}

最佳答案

所以我终于找到了如何让它发挥作用的方法。我希望我没有丢失昨晚阅读的博客的链接,因为我没有编写代码。

public T GetByPrimaryKey<T>(int id) where T : class
{
    return (T)_db.GetObjectByKey(new EntityKey(_db.DefaultContainerName + "." + this.GetEntityName<T>(), GetPrimaryKeyInfo<T>().Name, id));
}

string GetEntityName<T>()
{
    string name = typeof(T).Name;
    if (name.ToLower() == "person")
        return "People";
    else if (name.Substring(name.Length - 1, 1).ToLower() == "y")
        return name.Remove(name.Length - 1, 1) + "ies";
    else if (name.Substring(name.Length - 1, 1).ToLower() == "s")
        return name + "es";
    else
        return name + "s";
}

private PropertyInfo GetPrimaryKeyInfo<T>()
{
    PropertyInfo[] properties = typeof(T).GetProperties();
    foreach (PropertyInfo pI in properties)
    {
        System.Object[] attributes = pI.GetCustomAttributes(true);
        foreach (object attribute in attributes)
        {
            if (attribute is EdmScalarPropertyAttribute)
            {
                if ((attribute as EdmScalarPropertyAttribute).EntityKeyProperty == true)
                    return pI;
            }
            else if (attribute is ColumnAttribute)
            {

                if ((attribute as ColumnAttribute).IsPrimaryKey == true)
                    return pI;
            }
        }
    }
    return null;
}

我希望这对其他人有帮助。我只能说应该更清楚如何执行此操作。

关于c# - Entity Framework 4 : How to find the primary key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2958921/

相关文章:

c# - 除当前日期外,格式为 "ddd"的 DateTime.TryParseExact 在所有日期均失败

c# - 在 javascript 中引用 ASP.NET Web 控件

C# 从 Entity Framework 将顺序插入列表

entity-framework - 使用 Angular 2 时是否需要在 Typescript 中复制 Entity Framework 类?

c# - Entity Framework 和数据库列名

c# - 我想去掉除数字、$、逗号 (,) 以外的所有内容

c# - Asp.Net 从 PlaceHolder 获取控件值

C#创建类实例时执行类内的方法

c# - 内部接口(interface)实现

c# - 在异常处理中显示行号