gpt4 book ai didi

entity-framework - Automapper - 更新嵌套子集合时出错

转载 作者:行者123 更新时间:2023-12-02 02:01:52 24 4
gpt4 key购买 nike

我有一个使用代码优先 (POCO)、EF、ViewModels 和 AutoMapper 的 MVC 4 示例应用程序。我创建了一个 Controller ,其中父实体和相应的子实体位于同一 View (具有嵌套子实体集合的实体)。到目前为止看起来不错,只是我在更新记录时遇到问题。我收到以下错误:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

我已经在网上搜索了很多天,现在尝试了不同的解决方案,但无法正常工作。

我有以下领域模型:

public class Team
{
public int Id { get; set; }

public string Name { get; set; }

public virtual ICollection<Player> Players { get; set; }
}

public class Player
{
public int Id { get; set; }

public string Name { get; set; }

public int TeamId { get; set; }
public virtual Team Team { get; set; }
}

和相应的 View 模型:

public class TeamVM
{
public int Id { get; set; }

public string Name { get; set; }

public virtual ICollection<PlayerVM> Players { get; set; }
}

public class PlayerVM
{
public int Id { get; set; }

public string Name { get; set; }

public int TeamId { get; set; }
public virtual TeamVM Team { get; set; }
}

我的映射如下:

Mapper.CreateMap<Player, PlayerVM>();
Mapper.CreateMap<PlayerVM, Player>();
Mapper.CreateMap<Team, TeamVM>();
Mapper.CreateMap<TeamVM, Team>();

我的团队 Controller 编辑操作如下:

[HttpPost]
public ActionResult Edit(TeamVM teamVM)
{
if (ModelState.IsValid)
{
Team team = context.Teams.Find(teamVM.Id);
Team updatedTeam = Mapper.Map<TeamVM, Team>(teamVM, team);
context.Entry(team).CurrentValues.SetValues(updatedTeam);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(teamVM);
}

我在这里错过了什么?

最佳答案

关于异常的最后一部分:

or the unrelated object must be deleted

在您的 Edit 方法中,Player 似乎已从 team.Players 中删除(或者甚至可能由于复制失败而完全清除) .但是,太糟糕了,如果外键不可为空(显然,没有团队就不能存在玩家),您不能只从子集合中删除项目。您必须从上下文中删除已删除的玩家。

所以你必须检测从团队中移除的玩家,并为他们每个人调用

context.Players.Remove(player);

关于entity-framework - Automapper - 更新嵌套子集合时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16845591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com