开发者

Entity Framework v4 POCO templates: repository returns object of incorrect type

I've just implemented a repository based on EFv4 POCO entity templates.

When I do this

public Client Load(Guid firmId,
                   int prettyId)
{
    var client = (from c in _ctx.Clients where c.firm_id == firmId && c.PrettyId == prettyId select c).FirstOrDefault();
    return client;
}

the client returned is of type

{System.Data.Entity.DynamicProxies.Client_8E92CA62619EB03F03DF1A1F开发者_StackOverflowC60C5B21F87ECC5D85B65759DB3A3949B8A606D3}

What is happening here? I thought I would get rid of any reference to types from System.Data.Entity namespace. The returned instance should be of type Client, which is a simple POCO class.


I can confirm that the solution is to set

context.ProxyCreationEnabled = false;

which disables creation of dynamic proxy typed objects and leaves us with simple POCOs, which is what we were after with EF POCO templates in the first place.

But you lose lazy loading of navigation properties and change tracking on entities. For the first, you either have to use context.LoadProperty() or the Include() method on your ObjectQuery object. For the second, I do not know the solution yet (actually it doesn't really make sense to have change tracking on POCOs).

Also here is a similar question I would like to point out What are the downsides to turning off ProxyCreationEnabled for CTP5 of EF code first


I agree that Mare's answer is correct. However, I would add a note of caution. If you run a query without this ProxyCreationEnabled setting set to true, then EF will return DynamicProxies. If you subsequently run a query with the setting set to false, then EF will return the cached DynamicProxies objects, regardless of the ProxyCreationEnabled setting.


This can be configured globally for the EF context in the *Model.Context.tt file in *Model.edmx under

if (!loader.IsLazyLoadingEnabled(container))

...

    this.Configuration.LazyLoadingEnabled = false;
    this.Configuration.ProxyCreationEnabled = false;

These will be added to the *Model.context.cs generated file, and will persist between updates from the Database.

I prefer this setting as I do not want a child object that matches the parent loaded from the database.

ALT: It can be configured for Json serizialization: JSON.NET Error Self referencing loop detected for type

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜