获取未知实体的密钥

Get the key of an unknown entity

您好,我想获取主键值。

public static void Look(LEBAEntities db, object obj) {
    // if getPrimaryKey(obj) == 0
    db.Entry(obj).State = EntityState.Added;

    // else
    db.Entry(obj).State = EntityState.Modified;
} 

是否有函数或任何方法可以通过 Entity Framework 获取主键?

这里有几种解决方案:

1- 您的实体继承自 Base Class,其基础 class 具有 Id 属性,并且您使 Look 方法通用:

public abstract class BaseEntity
{
    protected BaseEntity()
    {
    }

    public virtual int Id { get; set; }
}

public static void Look<TEntity>(LEBAEntities db, TEntity entity) where TEntity : BaseEntity {
    if(entity.Id == 0)
        db.Entry(entity).State = EntityState.Added;
    else
        db.Entry(entity).State = EntityState.Modified;
}

2- 您可以通过反射使用 GetProperties 方法并比较 属性 名称:

public static void Look(LEBAEntities db, object obj) {
    var type = obj.GetType();
    var key = type.GetProperties().FirstOrDefault(p => 
        p.Name.Equals("ID", StringComparison.OrdinalIgnoreCase) 
        || p.Name.Equals(type.Name + "Id", StringComparison.OrdinalIgnoreCase)); 

    if(key == 0)
        db.Entry(obj).State = EntityState.Added;
    else
        db.Entry(obj).State = EntityState.Modified;
}

3 - 您可以询问映射元数据以获取密钥:

public static void Look(LEBAEntities db, object obj) {
    var type = obj.GetType();
    var type = typeof (IdentityUser);
    var objectContext = ((IObjectContextAdapter)context).ObjectContext;
    IEnumerable<string> retval = (IEnumerable<string>)objectContext.MetadataWorkspace
        .GetType(type.Name, type.Namespace, System.Data.Entity.Core.Metadata.Edm.DataSpace.CSpace)
        .MetadataProperties.First(mp => mp.Name == "Id")
        .Value;
.
.
.