POCO实体上的私有构造函数可防止延迟加载 [英] Private constructor on POCO entity preventing lazy loading

查看:82
本文介绍了POCO实体上的私有构造函数可防止延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个POCO实体,在该实体上定义了一个自定义构造函数.我还实现了默认构造函数,以便当我从数据库请求副本时,Entity Framework可以成功为对象充水.

I have a POCO entity on which I have defined a custom constructor. I have also implemented the default constructor so that Entity Framework can successfully hydrate the object when I request a copy from the database.

这似乎很好用,但是当我将默认构造函数设置为private(以强制我的代码使用自定义版本)并从数据库请求一个实体时,我似乎无法浏览相关实体,因为它们都是空的.

This seems to work well but when I set the default constructor to private (to force my code to use the custom version) and request an entity from the database, I don't seem to be able to navigate over related entities as they are all null.

这似乎是一个延迟加载问题,因此我可以更改存储库以渴望加载所需的相关对象,但想知道是否有更好的方法可以从客户端代码中隐藏默认构造函数,同时允许实体框架延迟加载?

This seems to be a lazy loading problem so I could change my repository to eager load the related objects I need but am wondering if there is a better way to hide the default constructor from the client code whilst allowing Entity Framework to lazy load?

推荐答案

如果定义私有构造函数,则违反创建负责延迟加载的POCO代理的要求:

If you define private constructor you violate requirements for creating POCO proxy responsible for lazy loading:

自定义数据类必须具有一个公共的或受保护的构造函数,该构造函数必须 没有参数.

A custom data class must have a public or protected constructor that does not have parameters.

因此,最适合您的选择是使用受保护的构造函数,或者不使用延迟加载.

So the best option for you is using protected constructor or not using lazy loading.

这篇关于POCO实体上的私有构造函数可防止延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆