Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 未保存现有实体上添加的导航属性_C#_Ef Core 2.0 - Fatal编程技术网

C# 未保存现有实体上添加的导航属性

C# 未保存现有实体上添加的导航属性,c#,ef-core-2.0,C#,Ef Core 2.0,查看以下代码: var existingBlog = ... // get existing blog somehow List<Post> newPosts = ... // get new posts somehow existingBlog.Posts.Add(newPosts); using (var context = new BloggingContext()) { context.Entry(existingBlog).State = EntityState.M

查看以下代码:

var existingBlog = ... // get existing blog somehow
List<Post> newPosts = ... // get new posts somehow
existingBlog.Posts.Add(newPosts);
using (var context = new BloggingContext())
{
    context.Entry(existingBlog).State = EntityState.Modified;
    context.SaveChanges();
}
var existingBlog=…//以某种方式获取现有博客
列出新帖子=…/以某种方式获得新的职位
现有blog.Posts.Add(newPosts);
使用(var context=new BloggingContext())
{
context.Entry(existingBlog.State=EntityState.Modified;
SaveChanges();
}

为什么新帖子没有添加到数据库中?

为什么这样使用?也许试着换一种方式

var existingBlog = ... // get existing blog somehow
using (var context = new BloggingContext())
{
    var newPost = new Post { Title = "some title", BlogId = existingBlog.Id };
    context.Add(newPost);
    context.SaveChanges();
}

你为什么那样用?也许试着换一种方式

var existingBlog = ... // get existing blog somehow
using (var context = new BloggingContext())
{
    var newPost = new Post { Title = "some title", BlogId = existingBlog.Id };
    context.Add(newPost);
    context.SaveChanges();
}

如果在开始跟踪后添加帖子呢

var existingBlog = ... // get existing blog somehow
List<Post> newPosts = ... // get new posts somehow
using (var context = new BloggingContext())
{
    context.Entry(existingBlog).State = EntityState.Modified;
    existingBlog.Posts.AddRange(newPosts);
    context.SaveChanges();
}
var existingBlog=…//以某种方式获取现有博客
列出新帖子=…/以某种方式获得新的职位
使用(var context=new BloggingContext())
{
context.Entry(existingBlog.State=EntityState.Modified;
现有blog.Posts.AddRange(newPosts);
SaveChanges();
}

如果在开始跟踪后添加帖子怎么办

var existingBlog = ... // get existing blog somehow
List<Post> newPosts = ... // get new posts somehow
using (var context = new BloggingContext())
{
    context.Entry(existingBlog).State = EntityState.Modified;
    existingBlog.Posts.AddRange(newPosts);
    context.SaveChanges();
}
var existingBlog=…//以某种方式获取现有博客
列出新帖子=…/以某种方式获得新的职位
使用(var context=new BloggingContext())
{
context.Entry(existingBlog.State=EntityState.Modified;
现有blog.Posts.AddRange(newPosts);
SaveChanges();
}

我知道我可以做到这一点,但事实上我有很多帖子要添加(请参阅我的更新),所以我应该循环这些帖子并将它们添加到上下文中。。。我以为会有一个更干净的方法…我知道我可以做到,但事实上我有很多帖子要添加(见我的更新),所以我应该循环它们并将它们添加到上下文中。。。我以为会有更干净的方法。。。