以下の例1は動作していましたが、EFコアでは機能しません。 質問:下記の例2をどのようにするには?EFコアに子レコードを持つ親レコードを追加する方法
例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は、1対1の関係で子供C1、及びC2を有しています。親レコードとその子レコードを挿入しようとしています。しかし、次のコードVS2017
のエディタのintellisense
は、の.child
を認識しません。おそらく、EFコアには、親子レコードを挿入するための優れた機能があります。私はASP.NET MVC Core 1.1.1
とEFコア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();
UPDATE:@GlennSills
から要求ごと
、以下ではよく知られているブログ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; }
}
以下方法は、ライン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コアでトランザクションを使用してみましたか? –
@ H.Herzlいいえ、私はしていません。それはどんなものでしょうか? – nam
あなたはアイデンティティを使用していますか? –