Convert POCO object to Proxy object in EntityFramework

此生再无相见时 提交于 2020-01-02 06:43:12

问题


I have a MVC3 Project and I have run into a problem. I have a Create controller which takes as a parameter one of my POCO objects. I add this object to the database like this:

  entity = dbSet.Add(entity);

After this method returns, I would like to use the lazy loading features of the object. Unfortunately the object is not a Proxy object generated by the EntityFramework...Is there a way to somehow solve this?

Thank You, AFrieze


回答1:


The entity must be already proxied when you pass it to Add method. Add method will not return another instance of the class and you cannot change the type of the existing instance to the proxy type.

Your options are:

  • Not using entity as input in controller - use some view model and populate new entity created by dbSet.Create - this will create empty proxied detached entity.
  • Instead of adding the entity received in controller create a new one by dbSet.Create and copy data from received one to created one
  • Don't use default model binder. Create custom model binder (that is the code responsible for extracting data from HTTP request and populating parameters passed to controller) which will use dbSet.Create instead of default entity constructor.


来源:https://stackoverflow.com/questions/8174200/convert-poco-object-to-proxy-object-in-entityframework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!