【发布时间】:2019-11-06 21:36:59
【问题描述】:
我的应用程序在使用 postgres 时遇到问题。 对于背景,我正在尝试实现此数据库模型:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<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 Blog Blog { get; set; }
}
我能够在 Postgres 中正确地创建数据库,将我的 .Net 应用程序连接到数据库等。唯一让我犹豫的是在我保存对象之后:
var blog = new Blog();
blog.Url = "UrlTest";
var post = new List<Post>();
var entry = new Post();
post.Title = "Entry Title";
post.Add(entry);
blog.Posts = post;
context.Blog.Add(blog);
context.SaveChanges();
只是简单的一对多关系。保存更改后,我查询上下文,它能够看到我刚刚创建的博客和帖子的关系。
不幸的是,当我重新启动我的 .Net Core 应用程序并尝试列出所有博客时,它将显示为空,但是当我转到数据库服务器并查询 Post 表时,我能够确认它仍然具有博客 ID。
我尝试了以下所有建议,但没有任何效果: Entity framework code-first null foreign key
编辑: 这是我的 DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>();
modelBuilder.Entity<Post>();
modelBuilder.Entity<Blog>()
.HasMany(c => c.Post)
.WithOne(c => c.Blog)
.HasForeignKey(c => c.BlogId)
.OnDelete(deleteBehavior: DeleteBehavior.Cascade);
base.OnModelCreating(modelBuilder);
}
public DbSet<Post> Posts { get; set; }
public DbSet<Blog> Blogs { get; set; }
我也尝试在博客模型中的列表和帖子模型中的博客上放置虚拟,但没有奏效
【问题讨论】:
-
您需要显示您的 DBContext 类以及您获取上下文并尝试获取列表的类
-
我们需要您运行查询的代码才能提供帮助
-
大家好,正在查看 docs.microsoft.com/en-us/ef/core/querying/related-data。急切加载效果很好,我将尝试找出为什么延迟加载在我的应用程序上不起作用。穆斯塔法,如果你愿意,把这个问题的答案放在这个问题上,这样我就可以回答了。
标签: asp.net-core entity-framework-core npgsql