How can I dynamically customize a POCO proxy in EF 4?

╄→гoц情女王★ 提交于 2019-12-13 00:28:33

问题


I would like to dynamically customize some POCO classes overriding myself the virtual members to be able to compile LINQ to Entities queries. I know about the ObjectMaterialized event but that happens after the class instantiation. I would like to be able to create the proxy myself, override the virtual members I want and then pass along to the EF, is that possible?

Imagine the following POCO class:

public class Consumer {
    /* That´s a virtual property with an association in EF */
    public virtual ICollection <Message> Messages { get; set; }

    /* That´s the business logic I would like to optimize. */
    public virtual Message GetMyLatestMessage()
    {
        return Messages.Where(m => m.Writer != null && m.Writer.ID == ID && m.Type == "Message")
                       .OrderByDescending(m => m.Date)
                       .Take(1)
                       .FirstOrDefault();
    }
 }

When I use this code against EF 4 the expression inside GetMyLatestMessage() becomes a SQL query, but I would like to pre-compile these expressions because some of them gets pretty slow to parse everytime.


回答1:


EF doesn't offer intercepting or replacing dynamic proxy generated for POCOs. Moreover what you show cannot be optimized because it is Linq-to-Objects. EF always loads all messages to memory first time you execute it. That is how navigation properties and lazy loading works and it is also probably reason for your performance problems.

If you want to make optimization exclude your GetMyLatestMessage from Consumer to separate class and use:

public Message GetLatestMessage(int consumerId)
{
    return context.Messages.Where(m => m.Consumer.Id == consumerId &&
                                       m.Writer != null && 
                                       m.Writer.ID == ID && 
                                       m.Type == "Message")
                  .OrderByDescending(m => m.Date)
                  .Take(1)
                  .FirstOrDefault();

}


来源:https://stackoverflow.com/questions/5464669/how-can-i-dynamically-customize-a-poco-proxy-in-ef-4

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