c# - EF Core 将实体连接到视图。一对多
问题描述
我有一个简单的项目来显示问题,我想连接ICollection<Post>
view View_BlogPosts
。这只是简化的场景,在现实生活中,我需要将实体与大视图与来自不同表的许多列连接起来。
代码中最有趣的部分是:OnModelCreating(ModelBuilder modelBuilder)
哪里有带有实体的配置视图:(Post
一个博客到多个帖子)。但它现在不起作用,这行代码:var test = db.BlogWithPosts.ToList();
返回空的帖子集合。
如何解决这个问题?
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Samples
{
public class Program
{
private static void Main()
{
SetupDatabase();
using (var db = new BloggingContext())
{
var test = db.BlogWithPosts.ToList();
}
}
private static void SetupDatabase()
{
using (var db = new BloggingContext())
{
if (db.Database.EnsureCreated())
{
db.Blogs.Add(
new Blog
{
Name = "Fish Blog",
Url = "http://sample.com/blogs/fish",
Posts = new List<Post>
{
new Post { Title = "Fish care 101" },
new Post { Title = "Caring for tropical fish" },
new Post { Title = "Types of ornamental fish" }
}
});
db.Blogs.Add(
new Blog
{
Name = "Cats Blog",
Url = "http://sample.com/blogs/cats",
Posts = new List<Post>
{
new Post { Title = "Cat care 101" },
new Post { Title = "Caring for tropical cats" },
new Post { Title = "Types of ornamental cats" }
}
});
db.Blogs.Add(
new Blog
{
Name = "Catfish Blog",
Url = "http://sample.com/blogs/catfish",
Posts = new List<Post>
{
new Post { Title = "Catfish care 101" }, new Post { Title = "History of the catfish name" }
}
});
db.SaveChanges();
db.Database.ExecuteSqlRaw(
@"CREATE VIEW View_BlogPosts AS
SELECT b.Name , b.BlogId, b.Url FROM Blogs b");
}
}
}
}
public class BloggingContext : DbContext
{
private static readonly ILoggerFactory _loggerFactory
= LoggerFactory.Create(
builder => builder.AddConsole().AddFilter((c, l) => l == LogLevel.Information && !c.EndsWith("Connection")));
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<BlogWithPosts> BlogWithPosts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(
// @"Server=(localdb)\mssqllocaldb;Database=Sample.KeylessEntityTypes;Trusted_Connection=True;ConnectRetryCount=0;")
@"Server=.\SQLEXPRESS;Database=test_view;Trusted_Connection=True;")
.UseLoggerFactory(_loggerFactory);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BlogWithPosts>(eb =>
{
//eb.HasNoKey();
eb.ToView("View_BlogPosts");
eb.HasKey(bwp => bwp.BlogId);
eb.Property(v => v.BlogName).HasColumnName("Name");
eb
.HasMany(bwp => bwp.Posts)
.WithOne()
.HasForeignKey(p => p.BlogId);
});
}
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public ICollection<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
}
public class BlogWithPosts
{
public int BlogId { get; set; }
public string BlogName { get; set; }
public ICollection<Post> Posts { get; set; } = new List<Post>();
}
}
编辑:
感谢@Neil W 的回答:
这很好,但之后var test = db.BlogWithPosts.Include(bwp => bwp.Posts).ToList();
仍然没有帖子。
我在运行程序后检查了数据库,在 Post 表中我发现,添加了第二个 ID:BlogId1
我已经像这样填写BlogId
了相同的列BlogId1
:
并且出现了帖子
但是如何设置第二个 id: 的配置BlogId1
不会出现。
解决方案
您需要在访问上下文时询问相关实体,使用包括:
var test = db.BlogWithPosts.Include(bwp => bwp.Posts).ToList();
推荐阅读
- reactjs - 一个
可能只有一个子元素。尝试了一切 - mysql - 从 MySQL 中提取所有 JSON 密钥
- swift - 从 CIImage 创建 UIImage 似乎总是失败
- android - Worker 下的多个 OneTimeWorkRequest 导致我的应用程序冻结
- python - 由于需要密码加密,Python Sqlanydb 无法连接到 Sybase
- python - 我想将噪声应用于由 3D numpy 数组描绘的体积
- r - R中带有条件语句的线性回归
- python - Keras:将 MDN 层添加到 LSTM 网络
- assembly - 系统调用在 virtualbox 中运行的 Linux debian 64 位的汇编中不起作用
- json - 在 Swift 4 中转换为 Codable 之前检查 JSON 对象键