ADO.NET实体框架IsLoaded和负载 [英] ADO.NET Entity Framework IsLoaded and Load
问题描述
我发现自己在使用ADO.NET实体框架重复code位这样一遍又一遍。
I find myself repeating bits of code like this over and over while using ADO.NET Entity Framework.
VB:
' Load the thing if not already loaded. '
If Not Something.Thing.IsLoaded Then
Something.Thing.Load()
End If
C#:
// Load the thing if not already loaded.
if (!Something.Thing.IsLoaded)
{
Something.Thing.Load();
}
这是正常的吗?我应该使用<一个href="http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.relatedend.isloaded.aspx"相对=nofollow> IsLoaded 和的加载如此频繁?还是我没有使用这个正确?
Is this normal? Should I be using IsLoaded and Load so often? Or am I not using this correctly?
推荐答案
中的EntityFramework中的 VS2010测试版是多少,在这方面更友好。也就是说,如果你坚持不懒加载的版本,该扩展方法可以帮助你:
The version of the EntityFramework in the VS2010 beta is much, much friendlier in this regard. That said, if you're stuck with the version without lazy-loading, this extension method may help you:
public static T EnsureLoaded<T>(this EntityReference<T> eRef) where T: class, IEntityWithRelationships
{
if (!eRef.IsLoaded)
eRef.Load();
return eRef.Value;
}
然后,假设你有一个有联系的用户对象,你可以这样做:
Then, assuming you have User objects that have Contacts, you could do:
Contact c = User.ContactReference.EnsureLoaded();
它仍然pretty的苏茨基,但我觉得preferable写作的IsLoaded如果声明了个遍。
It's still pretty sucky, but I find it preferable to writing that IsLoaded if statement over and over.
这篇关于ADO.NET实体框架IsLoaded和负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!