我有一个用SQL定义的名为Blog的表:
create table Blog
(
SurrogateKey uniqueidentifier not null primary key,
Text nvarchar(max)
)
和名为“注释”的第二个表
create table Comments
(
SurrogateKey uniqueidentifier not null primary key,
Comment nvarchar(max)
)
在EF中,我在C#中拥有实体Blog和Comment,例如:
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
然后我得到所有重复的评论数量的结果。为了提高性能,我希望注释作为字符串。并且应该可以查询注释。这样我就可以在博客和所有评论中得到一个结果。在SQL中,我会写:
select SurrogateKey, Text,
Comment = (select Comment
from comments where surrogateKey = blog.SurrogateKey
AND Comment like '%test%' FOR XML)
from Blog
是否可以对Enity Framework(3)核心执行相同的操作?这样我就可以将博客的评论转换为字符串? 并且转换应该在服务器端完成,而不是在我稍后将注释对象转换为字符串的查询上。