问题
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