[英]Adding new entity doesn't link to existing related entity, but creates new one instead
My problem is the following: I have a "Create new Game" form. 我的问题如下:我有一个“创建新游戏”表格。 Within that form, there is a dropdown populated with data (categories).
在该表格中,有一个下拉列表,其中填充了数据(类别)。 So each game belongs to one category and both games and categories are stored in a database.
因此,每个游戏都属于一个类别,并且游戏和类别都存储在数据库中。 However, the Insert of a game doesnt link that game to the selected category.
但是,插入游戏不会将该游戏链接到所选类别。 Instead, a completely new, nameless category is created and assigned to that game.
而是创建了一个全新的无名类别并将其分配给该游戏。
In the .cshtml file: 在.cshtml文件中:
<div class="editor-field">
@Html.DropDownListFor(model => model.Category.Id, GameManager.Controllers.GameController.AllCategories())
@Html.ValidationMessageFor(model => model.Category)
</div>
the game model: 游戏模型:
public class Game
{
public int Id { get; set; }
public String Name { get; set; }
public virtual Studio Studio { get; set; }
public virtual Category Category { get; set; }
public float Price { get; set; }
public int Downloads { get; set; }
public DateTime ReleaseDate { get; set; }
}
the category model: 类别模型:
public class Category
{
public int Id { get; set; }
public String Name {get; set;}
}
Edit: the controller 编辑:控制器
[HttpPost]
public ActionResult Create(Game game)
{
if (ModelState.IsValid)
{
db.Games.Add(game);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(game);
}
You need to load the category: 您需要加载类别:
game.Category = db.Categories.Single(c => c.Id == game.Category.Id);
db.Games.Add(game);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.