如何在实体框架中对FK属性应用预测?

时间:2012-08-20 13:38:20

标签: asp.net-mvc entity-framework linq-to-entities

使用此answer我现在可以将我的投影逻辑存储在Expression中,并在另一个投影中使用它。

然而,当我开始在我的解决方案中实现这个approch时,我发现,我无法在Navigation属性上使用存储的Expression,这是一个FK(不是集合)。< / p>

以下代码演示了此问题:

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, };
    }
}

是否可以使用Expression将单个FK导航属性转换为模型?

1 个答案:

答案 0 :(得分:2)

目前这种方式过于复杂:

p =>
new BlogPostModel
{
    ...,
    Author = new[] { p }.AsQueryable().Select(UserModelExtensions.ToModelConverterExpression).FirstOrDefault()
}

然而,生成的SQL虽然正确,但是不必要地复杂且缓慢。据我所知,还没有任何方法可以直接得到你想要的东西,但我一直在寻找同样的东西,而且我有一个概念验证补丁,用于开源即将成为EF-我计划提交包含的6.0,请参阅the discussion threadthe change