如何对实体框架中的FK属性应用预测? [英] How to apply projections on FK property in Entity Framework?
问题描述
使用此答案,我现在可以将我的投影逻辑存储在表达式
,并在另一个预测中使用。
Using this answer I am now able to store my projection logic in an Expression
and use it inside another projections.
然而,当我开始在我的解决方案中实现这个问题时,我发现我不能在导航属性上使用存储的表达式
,该属性是单个FK(不是集合)。
However, when I started to implement this approch in my solution, I found out, that I am not able to use the stored Expression
on a Navigation property which is a single FK (not a collection).
以下代码演示了此问题:
The following code demonstrates this issue:
namespace Entities
{
public class BlogPost
{
public virtual int BlogPostId { get; set; }
public virtual string Title { get; set; }
public virtual string NotUsed { get; set; }
public virtual User Author { get; set; }
}
public class User
{
public virtual int UserId { get; set; }
public virtual string Name { get; set; }
public virtual string NotUsed { get; set; }
public virtual ICollection<BlogPost> BlogPosts { get; set; }
}
}
namespace Models
{
public class BlogPostModel
{
public string Title { get; set; }
public UserModel Author { get; set; }
}
public class UserModel
{
public string Name { get; set; }
}
public static class BlogPostModelExtensions
{
public static readonly Expression<Func<BlogPost, BlogPostModel>> ToModelConverterExpression =
p =>
new BlogPostModel
{
Title = p.Title,
Author = null, //Problem!
// I need to convert User (p.Author) to UserModel using UserModelExtensions.ToModelConverterExpression
};
}
public static class UserModelExtensions
{
public static readonly Expression<Func<User, UserModel>> ToModelConverterExpression =
u => new UserModel{ Name = u.Name, };
}
}
是否可以将单个FK导航属性转换为模型使用表达式
?
Is it possible to convert single FK navigation property to a model using Expression
?
推荐答案
目前可能是一个过于复杂的方式:
This is currently possible in an overly complicated manner:
p =>
new BlogPostModel
{
...,
Author = new[] { p }.AsQueryable().Select(UserModelExtensions.ToModelConverterExpression).FirstOrDefault()
}
但是,生成的SQL正确的是不必要的复杂和缓慢。据我所知,目前还没有任何方式直接得到你想要的东西,但是我一直在寻找同样的东西,我有一个概念验证补丁,用于开源的EF- 6.0,我打算提交包含,请参阅讨论主题和更改。
However, the generated SQL, while correct, is needlessly complicated and slow. As far as I know, there is not yet any way to directly get what you want, but I've been looking for the same thing, and I have a proof-of-concept patch for the open source to-be-EF-6.0 that I plan to submit for inclusion, see the discussion thread and the change.
这篇关于如何对实体框架中的FK属性应用预测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!