我正在尝试插入一个与其他表有多对多关系的表。表格如下:
ID 是主键并具有自动递增。我首先创建数据库,然后使用命令搭建/生成实体。我想在表
NOVEL
中插入一条记录,同时具有流派。这是我的插入代码:
public async Task<IActionResult> Create(CreateNovelViewModel novelVM)
{
Novel novel = new Novel();
try
{
if (ModelState.IsValid)
{
novel.NovelTitle = novelVM.NovelTitle;
novel.NovelCover = "";
novel.NovelDescription = novelVM.NovelDescription;
novel.AuthorId = novelVM.AuthorID;
novel.UserId = novelVM.UserID;
foreach(var genreId in novelVM.Genres)
{
var genre = new Genre();
novel.Genres.Add(genreId);
}
_context.Add(novel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
else
{
ModelState.AddModelError("", "Không thể thêm.Hãy thử lại, nếu vấn đề còn tồn tại, liên hệ người có chuyên môn.");
}
}
catch (RetryLimitExceededException ex)
{
ModelState.AddModelError("", "Không thể thêm. Hãy thử lại, nếu vấn đề còn tồn tại, liên hệ người có chuyên môn.");
}
ViewBag.AuthorId = new SelectList(_context.Authors, "AuthorId", "AuthorName", novelVM.AuthorID);
ViewBag.UserId = new SelectList(_context.Users, "UserId", "UserId", novelVM.UserID);
ViewBag.GenreId = new SelectList(_context.Genres, "GenreId", "GenreName");
return View(novel);
}
代码运行正常,一条记录添加到
NOVEL
成功。但是我不知道为什么NOVEL_GENRE
表没有记录。我假设当时没有 novel
的 id,所以它不能插入到连接表中?
这是我的
Novel.cs
实体:
public partial class Novel
{
[Key]
public int NovelId { get; set; }
public string NovelTitle { get; set; } = null!;
public string NovelDescription { get; set; } = null!;
public string NovelCover { get; set; } = null!;
public DateTime NovelDatePost { get; set; } = DateTime.Now;
public int NovelView { get; set; } = 1;
public int AuthorId { get; set; }
public string UserId { get; set; } = null!;
public virtual Author Author { get; set; } = null!;
public virtual ICollection<Chapter> Chapters { get; } = new List<Chapter>();
public virtual User User { get; set; } = null!;
public virtual ICollection<UserComment> UserComments { get; } = new List<UserComment>();
public virtual ICollection<UserRating> UserRatings { get; } = new List<UserRating>();
public virtual ICollection<Genre> Genres { get; } = new List<Genre>();
}
这是
Genre.cs
实体:
public partial class Genre
{
public int GenreId { get; set; }
public string GenreName { get; set; } = null!;
public string GenreDescription { get; set; } = null!;
public virtual ICollection<Novel> Novels { get; } = new List<Novel>();
}
我刚开始使用 EF,所以我可能会错误地使用该功能。如果有人为此举了一些例子,我们将不胜感激。谢谢。