我使用 Entity Framework Core 2.0 并有这 2 个类:
消息
public class News
{
public int Id { get; set; }
public string Title{ get; set; }
public string Text { get; set; }
public DateTime ReleaseDate{ get; set; }
public int AuthorID{ get; set; }
public Author Author{ get; set; }
}
作者
public class Author
{
public Author ()
{
News = new List<News>();
}
public int Id { get; set; }
public string Username{ get; set; }
public string Firstname{ get; set; }
public string Lastname{ get; set; }
public ICollection<News> News {get;set;}
}
我只想用作者的用户名加载新闻,因为我不需要作者的名字和姓氏等其他信息。
如果我执行这个:
static void Main(string[] args)
{
using (var ctx = new DbContext())
{
var result= ctx.News.Include(x => x.Author).Select(news => new
{
news= news ,
Username= pr.Author.Username
}).ToList();
}
}
Entity Framework Core 2.0 生成一个数据库查询,如:
SELECT [x].[ID], [x].[Text], [x].[Title], [x].[AuthorId], [x].[ReleaseDate], [x.Author].[ID], [x.Verfasser].[Username] AS [Username], [x.Verfasser].[Firstname], [x.Verfasser].[Lastname]
FROM [News] AS [x]
INNER JOIN [Author] AS [x.Author] ON [x].[AuthorId] = [x.Author].[ID]
有没有办法实现我的预期行为?
最佳答案
如果我理解正确,您不想加载 Author
实体(因为无法加载仅填充一些非导航属性的实体)。
那么问题来了,你为什么特意加了Include(x => x.Author)
请求 EF 加载 Author
. Include
/ThenInclude
方法支持相关数据实体的预先加载。使用投影 ( Select
) 时不需要它们。
有趣的是,EFC 2.0 之前的所有 EF (Core) 版本都忽略了投影类型查询的包含。即使当前的 EFC 文档也指出投影查询属于 Ignored Includes类别。但是,正如您所注意到的,EFC 2.0 并没有忽略它!所以它要么是实现错误并将被修复,要么是文档错误并将被更新。
现在,请不要使用 Include
在投影查询中。如果你执行这个:
var result = ctx.News.Select(news => new
{
news = news,
Username = news.Author.Username
}).ToList();
现在 EFC 生成的 SQL 查询符合预期:
SELECT [news].[Id], [news].[AuthorID], [news].[ReleaseDate], [news].[Text], [news].[Title], [news.Author].[Username]
FROM [News] AS [news]
INNER JOIN [Authors] AS [news.Author] ON [news].[AuthorID] = [news.Author].[Id]
关于entity-framework-core - 从 Entity Framework 核心中的包含属性中选择特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46476117/