这是我的团队模型
public partial class TeamModel
{
public TeamModel()
{
this.Players = new HashSet<PlayerModel>();
}
public int TeamModelId { get; set; }
public string TeamName { get; set; }
public int SchoolId { get; set; }
public int DivisionId { get; set; }
public LogModel TeamLog { get; set; }
[ForeignKey("Under")]
public int UnderId { get; set; }
public virtual LogModel Log { get; set; }
public virtual SchoolModel School { get; set; }
public virtual DivisionModel Division { get; set; }
public virtual UnderModel Under { get; set; }
public virtual ICollection<PlayerModel> Players { get; set; }
这是我的日志模型
public class LogModel
{
[Key]
[ForeignKey("Team")]
public int TeamId { get; set; }
public int Played { get; set; }
public int Win { get; set; }
public int Draw { get; set; }
public int Lost { get; set; }
public int GoalsFor { get; set; }
public int GoalsAgainst { get; set; }
public int GoalDifference { get; set; }
public int Points { get; set; }
[ForeignKey("Season")]
public int SeasonId { get; set; }
public virtual SeasonModel Season { get; set; }
public virtual TeamModel Team { get; set; }
}
这是我在其中创建新团队的地方,也是在此过程中尝试为该特定团队创建新日志的地方。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "TeamModelId,TeamName,SchoolId,DivisionId,UnderId")] TeamModel teamModel)
{
teamModel.TeamLog = new LogModel();
teamModel.TeamLog.Draw = 0;
teamModel.TeamLog.GoalDifference = 0;
teamModel.TeamLog.GoalsAgainst = 0;
teamModel.TeamLog.GoalsFor = 0;
teamModel.TeamLog.Lost = 0;
teamModel.TeamLog.Played = 0;
teamModel.TeamLog.Points = 0;
teamModel.TeamLog.Win = 0;
teamModel.TeamLog.SeasonId = db.Seasons.ToList().Last().SeasonId;
db.Teams.Add(teamModel);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DivisionId = new SelectList(db.Divisions, "DivisionId", "DivisionName", teamModel.DivisionId);
ViewBag.SchoolId = new SelectList(db.Schools, "SchoolId", "SchoolName", teamModel.SchoolId);
ViewBag.UnderId = new SelectList(db.Under, "UnderID", "UnderName", teamModel.UnderId);
return View(teamModel);
}
当我尝试向团队中添加新日志时遇到的错误是
System.Data.Entity.Infrastructure.DbUpdateException:'一个错误 保存不公开外键的实体时发生 关系的属性。 EntityEntries属性将 返回null,因为无法将单个实体标识为源 例外。可以在保存时处理异常 通过在实体类型中公开外键属性,可以更轻松地进行操作。看到 有关详细信息,请参见InnerException。
,内部异常是
UpdateException:无法确定依赖项的有效顺序 操作。由于外键约束,可能存在依赖关系, 模型要求或商店生成的值。
我在互联网上寻找解决方案,但找不到任何可行的方法。我认为我的问题是我如何寻找解决方案。我搜索了错误,但似乎解决方案无法解决我在这里遇到的问题。创建团队时,我花了几天时间尝试创建日志。