我正在使用ASP.NET Core MVC + EF Core开发演示应用程序。
答案 0 :(得分:0)
EF Core将帮助填充SaveChangesAsync
函数之后的identity列的值。例如:
Author.cs:
public class Author
{
public int AuthorId { get; set; }
public string AuthorName { get; set; }
public List<BlogPost> BlogPosts { get; set; }
}
BlogPost.cs:
public class BlogPost
{
public int BlogPostId { get; set; }
public string BlogPostName { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
在创建作者动作中,EF Core将在保存后帮助填充AuthorId:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("AuthorId,AuthorName")] Author author)
{
if (ModelState.IsValid)
{
_context.Add(author);
await _context.SaveChangesAsync();
//here you will get id
var id = author.AuthorId;
//redirect to another action with parameter
return RedirectToAction(nameof(Index),new { id=id});
}
return View(author);
}
然后,您将使用参数重定向到另一个操作/视图,如上面的代码所示。
答案 1 :(得分:0)
“但是我还不知道该ID,因为它是由EF生成的。我也不知道如何传递它。”
author.Author =“ AuthorName”;
db.SaveChanges();
int id = author.AuthorId;
然后通过:
RedirectToAction(“ BlogPostView”,“ Controller”,id);