【发布时间】:2017-10-07 08:13:18
【问题描述】:
下面的示例 1 曾经可以工作,但它在 EF Core 中不工作。 问题:如何使下面的示例 2 工作?
示例 1:
child c1 = new child();
child c2 = new child();
parent p=new parent();
p.child.Add(c1);
p.child.Add(c2);
using (var db = new DbContext())
{
db.parent.Add(p);
db.SaveChanges();
}
实体父 P 具有一对一关系的子 C1 和 C2。尝试插入父项及其子项记录。但是在下面的代码中VS2017 的编辑器intellisense 在cust.child.Add(c1); 行无法识别.child。也许,EF Core 有更好的方法来插入父/子记录。我正在使用 ASP.NET MVC Core 1.1.1 和 EF Core 1.1.1。
示例 2:
...
Parent p = new Parent { Name = "some name" , FY = SelectedYear, ... };
Child c1 = new Child { ItemName = "Abc"};
Child c2 = new Child { ItemName = "Rst"};
p.child.Add(c1);
p..child.Add(c2);
_context.Add(p);
_context.SaveChanges();
更新:
根据@GlennSills 的请求,以下是著名的 Blogging Db 示例(取自this ASP.NET 教程):
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
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; }
}
在下面的Create(...) 方法中,在blog.Posts.Add(c); 行出现错误:Object reference not set to an instance of an object.
public class BlogsController : Controller
{
private readonly BloggingContext _context;
public BlogsController(BloggingContext context)
{
_context = context;
}
....
....
// POST: Blogs/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("BlogId,Url")] Blog blog)
{
if (ModelState.IsValid)
{
Post c = new Post();
blog.Posts.Add(c);
_context.Add(blog);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(blog);
}
}
【问题讨论】:
-
你试过在 ef core 中使用事务吗?
-
@H.Herzl 不,我没有。那会是什么样子?
-
你在使用身份吗?
-
您需要提供这两个实体(Parent 和 Child)的代码,才能正确回答此问题。如果您已正确设置这两个类之间的关系,则示例 1 有效。
-
@GlennSills 我倾向于同意你的观点。我添加了一个 UPDATE 部分来提供一个真实的例子。如果我在实际场景中使用示例 1,则会收到 UPDATE 部分中显示的错误。示例 1 似乎需要稍作调整。
标签: asp.net-core entity-framework-core