我已经没有关于如何让这段代码按照我想要的方式工作的想法了。我有 3 个模型,如下所述。
UserProfile and Player
一对一的关系
首先创建 UserProfile,在注册时将 emailConfirmation 发送到用户提供的电子邮件。一旦他们确认了他们的帐户,他们就会被重定向到他们的第一个登录页面,如果经过身份验证,他们会被重定向到创建新玩家页面,以提供有关他们扩展资料的更多信息。在创建页面上,我希望UserId
登录用户与即将创建的播放器相同。当我按原样尝试代码时,没有响应,也没有添加或保存到数据库中。
Team and Player
一对多关系
几乎不言自明,一个球员必须属于一个团队。这使得重定向到编辑操作成为不行Player.TeamId != null
。
用户资料
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public virtual Player Player { get; set; }
}
团队
public class Team
{
[Key]
[HiddenInput(DisplayValue = false)]
public int TeamId { get; set; }
[Display(Name = "Full Name:")]
public string Name { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
播放器
public class Player
{
[Key]
[ForeignKey("UserProfile")]
[HiddenInput(DisplayValue = false)]
public int UserId { get; set; }
[Required]
[Display(Name = "Full name")]
public string FullName{ get; set; }
[Display(Name = "Team")]
public int TeamId { get; set; }
public virtual Team Team { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
保存播放器
public void SavePlayer(Player player)
{
using (var context = new EFootballDb())
{
if (player.UserId == 0)
{
context.Players.Add(player);
}
else if (player.UserId > 0)
{
var currentPlayer = context.Players
.Single(t => t.UserId == player.UserId);
context.Entry(currentPlayer).CurrentValues.SetValues(player);
}
context.SaveChanges();
}
}
创建动作
[HttpGet]
public ActionResult Create()
{
PopulateTeamsDropDownList();
return View();
}
[HttpPost]
public ActionResult Create(Player model)
{
try
{
if (ModelState.IsValid)
{
_dataSource.SavePlayer(model);
return RedirectToAction("Detail", "Team", new { id = model.TeamId });
}
}
catch (Exception)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
PopulateTeamsDropDownList(model.TeamId);
return View(model);
}
private void PopulateTeamsDropDownList(object selectedTeams = null)
{
var teamsQuery = from d in _dataSource.Teams
orderby d.Name
select d;
ViewBag.TeamID = new SelectList(teamsQuery, "TeamId", "Name", selectedTeams);
}
一切都很好,Team and Player
但我无法UserProfile and Player
在 Creation 连接。有没有人有我应该尝试的想法或不同的方法?提前致谢!