【问题标题】:EF core get additional table entries as one json columnEF 核心获取额外的表条目作为一个 json 列
【发布时间】:2020-02-17 10:51:54
【问题描述】:

我有一个用 SQL 定义的名为 Blog 的表:

create table Blog
(
  SurrogateKey uniqueidentifier not null primary key,
  Text nvarchar(max)
)

还有一个名为 Comments 的表:

create table Comments
(
  SurrogateKey uniqueidentifier not null primary key,
  Comment nvarchar(max)
)

在 EF 中,我在 C# 中有实体博客和评论,例如:

internal class Blog
{
   public Guid SurrogateKey {get;set;}
   public string Text {get;set;}
   public ICollection<Comment> {get;set;}
   // what I want as json or xml
   // public string Comments {get;set;}
}

internal class Comment
{
  public Guid SurrogateKey {get;set;}
  public string Comment {get;set;}
}

还有一个上下文,例如:

internal class BlogContext : DBContext
{
  ....

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
     modelBuilder.Entity<Blog>().HasKey(blog => blog.SurrogateKey);
     modelBuilder.Entity<Blog>().ToTable("Blog");
     modelBuilder.Entity<Comment>().HasKey(comment=> comment.SurrogateKey);
     modelBuilder.Entity<Comment>().ToTable("Comment");
     modelBuilder.Entity<Blog>().HasMany(item => item.Comments)
             .WithOne().HasForeignKey(comment => comment.SurrogateKey);
  }
}

EF 然后创建一个像这样的连接:

select SurrogateKey, Text, Comment from Blog
join Comments on Blog.SurrogateKey = Comments.SurrogateKey 

然后我得到所有与 cmets 数量重复的结果。为了性能,我希望将 cmets 作为字符串。并且应该可以查询 cmets。这样我就可以通过博客和所有 cmets 获得一个结果。在 SQL 中我会写:

select SurrogateKey, Text, 
Comment = (select Comment 
           from comments where surrogateKey = blog.SurrogateKey 
           AND Comment like '%test%' FOR XML)
from Blog

是否可以对 Enity Framework (3) 核心做同样的事情?这样我就可以将博客的 cmets 转换为字符串? 并且转换应该在服务器端完成,而不是我稍后将 cmets 对象转换为字符串的查询。

【问题讨论】:

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


    【解决方案1】:

    您可以使用Keyless Entity Type 在模型中注册 SQL 视图。

    【讨论】:

    • 我不确定它是否能解决所有问题。根据您的回答,我看到我没有明确表示我也想过滤 cmets。我将此添加到问题中。适合无钥匙实体吗?目前我还没有让它运行。如何传递我获得适合博客的 cmets 的 SurogateKey?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2020-05-05
    相关资源
    最近更新 更多