c# - Entity Framework 仅包含/选择不同表中的某些属性

标签 c# entity-framework entity-framework-core dbcontext

假设我有一个名为 GetThreadWithComments() 的方法。每个线程都有 1 个用户(创建者)并有一个评论列表。每个评论有 1 个用户(发布者)。

以下是类(由 EF 生成):

public class Thread
{
    public int ThreadId { get; set; }
    public int UserId { get; set; }
    public string Message { get; set; }

    public List<Comment> Comments { get; set; }
    public User User { get; set; }
}

public class Comment
{
    public long CommentId { get; set; }
    public string Message { get; set; }
    public int UserId { get; set; }
    public int ThreadId { get; set; }

    public User User { get; set; }
}

所以基本上,我想加载一个包含用户信息的线程,以及与用户信息相关联的评论。我试过这样的事情:

db.Threads.Select(x => new
{
    x,
    x.User = new { x.User.Username, x.User.Email },
    x.Comments = x.Comments.Select(c => new
    {
        c.Message,
        c.CommentId,
        c.User = new { c.User.Username, c.User.Email }
    })
});

以上是行不通的。但是,我不太确定如何正确执行此操作。我可以使用 include,但这会生成所有属性。由于速度是一个问题,我试图让事情尽可能轻松。

它不起作用的原因:它不构建。编译时错误。我得到的 2 个错误是:

Cannot implicitly convert type '' to...

CS0746 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

最佳答案

首先定义实体关系为virtual,例如

public User User { get; set; }

应该是

public virtual User User { get; set; }

其次,如果稍后发布的编译器错误,请尝试添加成员名称。

所以代替

x.User = new { x.User.Username, x.User.Email }

使用

x.User = new { 用户名 = x.User.Username, Email = x.User.Email }

还有太多的 x 在那里。更正后的示例是:

db.Threads.Select(x => new
{
    x,
    User = new { Username = x.User.Username, Email = x.User.Email },
    Comments = x.Comments.Select(c => new
    {
        c.Message,
        c.CommentId,
        User = new { Username = c.User.Username, Email = c.User.Email }
    })
});

关于c# - Entity Framework 仅包含/选择不同表中的某些属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48760707/

相关文章:

C# 从sql server导出到excel

c# - EF 4.0 实体属性 setter 抛出 ArgumentOutRangeException

c# - Entity Framework 核心: unhandled exception

c# - Entityframework Core 无法将类型为 'System.Int32' 的对象转换为类型 'System.Int64'

asp.net-core - ASP.NET Core SQL 连接超时

c# - Web 上下文中静态属性的影响

c# - MSIL - 操作码 conv.ovf.u8.un 如何工作?

没有客户端证书的 c# TLS 客户端

c# - asp.net mvc api返回 'This XML file does not appear to have any style information associated with it. The document tree is shown below.'

c# - 使用 WebApi 和映射模型实现 OData