在许多带有EF Core教程的ASP.NET Core(例如this)中,我们看到了Blogging数据库示例,我看到了两种向Blogs表添加记录的方法。有什么不同,哪个更好?下面的第一个示例使用_context.Add(blog);
,第二个示例使用context.Blogs.Add(blog);
VS2017
使用this教程生成的代码的快照:
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)
{
_context.Add(blog);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(blog);
}
}
{p> 添加this EF教程的数据示例:
using (var context = new BloggingContext())
{
var blog = new Blog { Url = "http://sample.com" };
context.Blogs.Add(blog);
context.SaveChanges();
Console.WriteLine(blog.BlogId + ": " + blog.Url);
}