添加带有模型对象EFModelFirst链接的模型

时间:2011-04-19 15:50:50

标签: c# .net asp.net asp.net-mvc-3 entity-framework-4.1

所以我有两个模型:人物和成分,我想要完成的事情是任何人都可以选择一种成分(通过jQuery自动完成),输入他们的数据,然后创建它将其保存到数据库。

所以它会是这样的:

    public class Person {

            public int PersonID { get; set; }

            [Required(ErrorMessage="Given name is a required field")]
            [DisplayName("Given name")]
            public string GivenName { get; set; }

            [Required(ErrorMessage="Family name is a required field")]
            [DisplayName("Family name")]
            public string FamilyName { get; set; }

            [Required(ErrorMessage = "Birthdate is a required field")]
            [DisplayFormat(DataFormatString = "{0:d}")]
            public DateTime Birthdate { get; set; }

            [DisplayName("Ingredient")]
            public virtual Ingredient Ingredient { get; set; }
    }

public class Ingredient {
    public int IngredientID { get; set; }

    [Required(ErrorMessage = "Ingredient is a required field")]
    [Remote("IngredientExists", "Person")]
    public string Name { get; set; }

    public virtual ICollection<Person> Persons { get; set; }
}

现在我的观点看起来像这样: (只是成分部分的片段)

    <div class="editor-label">
    @Html.LabelFor(model => model.Ingredient)
</div>
    <div id="ingredients-list" class="editor-field">        
    @Html.EditorFor(model => model.Ingredient.Name)
        @Html.ValidationMessageFor(model => model.Ingredient.Name)
        @ViewBag.IngredientError
</div>

控制器:

//
// POST: /Person/Create

[HttpPost]
public ActionResult Create(Person person) {
    if (ModelState.IsValid) {
        db.People.Add(person);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    person.Ingredient.Name = "";

    return View(person);
}

现在这一切都有效,除了1件事(一个主要问题),当我从我的下拉列表中选择一个成分时,它会保存人并在数据库中创建一个新的成分,其中包含一个新的ID和与该成分相同的值选择(即:重复)。 现在,我对EF和LINQ都很陌生,所以我还没想出如何做到这一点。任何想法/解决方案将不胜感激!

3 个答案:

答案 0 :(得分:1)

假设名称确实是唯一的,那么您只需选择用户选择的成分:

var ingredient = db.Ingredients.Single(i => i.Name == name); //throws exception if more than one ingredient with that name excists
person.Ingredient = ingredient;
db.Persons.Add(person)

答案 1 :(得分:0)

我建议使用外键支持。在您的个人模型上创建一个IngredientID属性,然后将该属性设置为您的Ingredient模型中的主键IngredientID。也许IngredientID可以绑定到下拉项的值属性

public class Person {
  public int IngredientID { get; set; }
}

答案 2 :(得分:0)

如果你这样称呼:

context.People.Add(person);

你说的是EF那个人是一个必须插入的新实体,但同时你说的是所有没有附加到上下文的相关实体也是新的。

如果您只想添加个人,可以尝试这样做:

context.People.Attach(person);
context.Entry(person).State = EntityState.Added;