【发布时间】:2020-07-12 20:56:45
【问题描述】:
我正在尝试使用 EF Core Code First 在我的 Game 表中创建一条新记录。它与Genre、Developer、Publisher 和Platform 共享一对多关系。
我正在为游戏/创建视图使用一个名为 GameCreateViewModel 的视图模型,它包含一个 Game 属性以及与每个外键对应的选择列表的属性,例如List<SelectListItem> Genres.
我遇到的问题是当我尝试创建一个新的Game 时,它给了我这个错误:
Microsoft.EntityFrameworkCore.DbUpdateException
HResult=0x80131500
Message=An error occurred while updating the entries. See the inner exception for details.
Source=Microsoft.EntityFrameworkCore.Relational
StackTrace:
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(DbContext _, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at GameSource.Data.Repositories.GameRepository.Insert(Game game) in E:\Tom\source\repos\My Projects\GameSource\GameSource.Data\Repositories\GameRepository.cs:line 35
at GameSource.Services.GameService.Insert(Game game) in E:\Tom\source\repos\My Projects\GameSource\GameSource.Services\GameService.cs:line 29
at GameSource.Controllers.GamesController.Create(GameCreateViewModel viewModel) in E:\Tom\source\repos\My Projects\GameSource\GameSource\Controllers\GamesController.cs:line 88
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table 'Developer' when IDENTITY_INSERT is set to OFF.
Cannot insert explicit value for identity column in table 'Genre' when IDENTITY_INSERT is set to OFF.
Cannot insert explicit value for identity column in table 'Platform' when IDENTITY_INSERT is set to OFF.
Cannot insert explicit value for identity column in table 'Publisher' when IDENTITY_INSERT is set to OFF.
游戏模型类:
public class Game
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public Genre Genre { get; set; }
public Developer Developer { get; set; }
public Publisher Publisher { get; set; }
public string Description { get; set; }
public Platform Platform { get; set; }
}
体裁模型类:
public class Genre
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
GameCreateViewModel:
public class GameCreateViewModel
{
public Game Game { get; set; }
public List<SelectListItem> Genres { get; set; }
public List<SelectListItem> Developers { get; set; }
public List<SelectListItem> Publishers { get; set; }
public List<SelectListItem> Platforms { get; set; }
}
游戏/创建视图 - 仅限类型选择列表的代码,其他选择列表重复相同的格式:
@model GameSource.ViewModels.GameViewModel.GameCreateViewModel
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Game.ID" />
<div class="form-group">
<label asp-for="Game.Name" class="control-label"></label>
<input asp-for="Game.Name" class="form-control" />
<span asp-validation-for="Game.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Game.Genre" class="control-label"></label>
<select asp-for="Game.Genre.ID" asp-items="@Model.Genres" class="form-control">
<option value="">Select a Genre/Genres</option>
</select>
<span asp-validation-for="Game.Genre" class="text-danger"></span>
</div>
游戏/创建控制器:
[HttpGet]
public IActionResult Create()
{
GameCreateViewModel viewModel = new GameCreateViewModel();
viewModel.Game = new Game();
viewModel.Genres = genreService.GetAll().Select(x => new SelectListItem()
{
Text = x.Name,
Value = x.ID.ToString()
}).ToList();
viewModel.Developers = developerService.GetAll().Select(x => new SelectListItem()
{
Text = x.Name,
Value = x.ID.ToString()
}).ToList();
viewModel.Publishers = publisherService.GetAll().Select(x => new SelectListItem()
{
Text = x.Name,
Value = x.ID.ToString()
}).ToList();
viewModel.Platforms = platformService.GetAll().Select(x => new SelectListItem()
{
Text = x.Name,
Value = x.ID.ToString()
}).ToList();
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(GameCreateViewModel viewModel)
{
Game game = new Game
{
ID = viewModel.Game.ID,
Name = viewModel.Game.Name,
Genre = viewModel.Game.Genre,
Developer = viewModel.Game.Developer,
Publisher = viewModel.Game.Publisher,
Description = viewModel.Game.Description,
Platform = viewModel.Game.Platform
};
gameService.Insert(game);
return RedirectToAction("Index");
}
它似乎也在尝试为外键插入一个新条目,即使我只是想将现有 ID 用于新的 Game 条目。例如。新的Game 的 GenreID 为 1,因此它应该引用 ID 为 1 的现有 Genre 条目。
非常感谢您对此的任何见解。另外,如果您也需要查看服务和回购方法,请告诉我。感谢您的宝贵时间。
【问题讨论】:
-
Game对象中的ID属性标记为Key,因此您不能显式插入ID,它由数据库自动递增。还始终将您的 id 属性命名为:GameID、GenreID这样当一个实体依赖于另一个实体时,ef core 可以正确设置外键。 -
你只是尝试插入嵌套表。请显示游戏的表结构?
-
-
据我所知,@HMZ EF Core 已正确映射出表格。它是否具有
Key属性并不重要,因为 EF Core 已经知道 ID 属性是该类的主键。这是我发现的地方:learnentityframeworkcore.com/conventions#primary-key 这是Game表的设计截图:i.gyazo.com/ce3e8e52c5bdf7a56c9c12f092cf0964.png -
@LDS 下面是
Game表的设计截图:i.gyazo.com/ce3e8e52c5bdf7a56c9c12f092cf0964.png
标签: c# asp.net-core entity-framework-core