问题描述
我已经在我的通用存储库中创建了通用 ObjectSet< T>
。
I've created a generic ObjectSet<T>
in my generic repository.
我想要什么得到的是 ObjectSet< T>
的EntityKey的名称
,这样我就可以在 DataContext.GetObjectByKey
。
What I would like to get is the name
of the EntityKey of ObjectSet<T>
so that I can use it in the DataContext.GetObjectByKey
.
我已经四处搜寻并深入挖掘了,但似乎无法在任何地方找到此值 ObjectSet
类。
I've searched around and dug deep, but I can't seem to find this value anywhere in the ObjectSet
class.
推荐答案
我前一阵子很不错做到这一点的方法,但没有找到。我通常最终会在其中的某个位置和其中构建一个GetEntityByKey扩展方法,污染字符串以为TryGetObjectByKey调用构建实体键。构建实体密钥的一般想法如下:
I looked a while ago for a nice way to do this and failed to find one. I generally end up building a GetEntityByKey extension method somewhere and within that, contatenating strings to build Entity Keys for TryGetObjectByKey calls. The general idea for building the entity key goes something like this:
internal class Program
{
private static void Main(string[] args)
{
var dc = new AdventureWorksLT2008Entities();
object c;
dc.TryGetObjectByKey(GetEntityKey(dc.Customers, 23), out c);
var customer = c as Customer;
Console.WriteLine(customer.EmailAddress);
}
private static EntityKey GetEntityKey<T>(ObjectSet<T> objectSet, object keyValue) where T : class
{
var entitySetName = objectSet.Context.DefaultContainerName + "." + objectSet.EntitySet.Name;
var keyPropertyName = objectSet.EntitySet.ElementType.KeyMembers[0].ToString();
var entityKey = new EntityKey(entitySetName, new[] {new EntityKeyMember(keyPropertyName, keyValue)});
return entityKey;
}
}
您也许可以做类似的事情。为了简单起见,此示例假设每个EntityKey具有单个字段-对于多个值键,您需要使用 ObjectSet< T> .ElementType.KeyMembers
进行稍微复杂一些的操作,并将所有键进入EntityKey构造函数。
You may be able to do something similar. This example assumes a single field per EntityKey for simplicity - for multiple value keys you would need to do something slightly more sophisticated with ObjectSet<T>.ElementType.KeyMembers
and pass all your keys into the EntityKey constructor.
这篇关于如何获得ObjectSet< T>的实体键名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!