本文介绍了如何在Entity Framework 4.1中获取主键,即使用DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到的答案是针对ObjectContext的.使用DbContext时是否具有确定实体的主键名称的属性?

The answers I'm seeing here are for ObjectContext. Is there a property to determine an entity's primary key names when using DbContext?

啊..我希望实体框架是开源的那一次!我可以从.Find方法中收集此主键名称信息:-)

Ah.. one of those times that I wish Entity Framework is open source! I can glean this primary key name information from .Find method :-)

推荐答案

您不能为此使用DbContext-DbContext API只是愚蠢的包装,仅具有最需要的功能.对于更复杂的一切,您必须将DbContext转换回ObjectContext并使用它.尝试这样的事情:

You cannot use DbContext for that - DbContext API is just dumb wrapper with only most needed functionality. For everything more complex you must convert DbContext back to ObjectContext and use it. Try something like this:

提取键名:

public static string[] GetEntityKeyNames<TEntity>(this DbContext context) where TEntity : class
{
  if (context == null)
    throw new ArgumentNullException("context");

  var set = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet<TEntity>();
  var entitySet = set.EntitySet;
  return entitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
}

这是一种提取实体的键值的方法:

Here's a method that will extract the key values of an entity:

public static IEnumerable<object> GetEntityKeys<TEntity>(this DbContext context, TEntity entity)
  where TEntity : class
{
  if (context == null)
    throw new NullReferenceException("context");

  var type = typeof(TEntity);

  var set = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet<TEntity>();
  var entitySet = set.EntitySet;
  var keys = entitySet.ElementType.KeyMembers;
  var props = keys.Select(k => type.GetProperty(k.Name));
  return props.Select(p => p.GetValue(entity));
}

这篇关于如何在Entity Framework 4.1中获取主键,即使用DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 03:19