简体   繁体   English

添加新实体不会链接到现有的相关实体,而是创建一个新实体

[英]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.

相关问题 实体框架:将现有子POCO添加到新的父POCO,在DB中创建新子项 - Entity Framework: adding existing child POCO to new Parent POCO, creates new child in DB 实体添加新ID而不是使用现有ID - Entity adds new IDs instead using existing one 分配实体实例而不是实体 id 创建新记录 - Assigning entity instance instead of entity id creates new record 更改实体也会创建一个新实体 - Changing an Entity creates a new one as well 防止在实体框架中的相关表实体上添加新记录 - Prevent Adding New Record on Related Table Entity in Entity Framework 使用外键发布新实体会导致创建另一个外部实体而不是引用现有实体 - Posting a new entity with foreign key causes creating another foreign entity instead of referencing existing one 为什么数据库中的新元素不想将自己分配给现有外键而是创建一个新元素? - Why a new element in the database doesn't want to assign itself to an existing foreign key but creates a new one? EF6创建新实体,而不只是设置参考 - EF6 creates new entity instead of setting just a reference 更新现有孩子而不是添加新孩子 - Updating existing child instead of adding new one 向实体添加新的构造函数 - Adding new constructors to entity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM