使用这个答案,我现在可以将我的投影逻辑存储在一个中Expression
并在另一个投影中使用它。
但是,当我开始在我的解决方案中实现此方法时,我发现我无法使用存储Expression
在作为单个 FK(不是集合)的 Navigation 属性上的内容。
下面的代码演示了这个问题:
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 导航属性转换为模型Expression
?