2011-04-19 55 views
0

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

因此,这将是这样的:

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相当陌生,所以我还没有想出如何做到这一点。任何想法/解决方案将不胜感激!

+0

如果要添加唯一的人,可以改为试试这个。类似的问题被问了100次,所以尝试使用搜索。 – 2011-04-19 16:15:30

回答

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) 
0

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

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

我真的不知道如何实现这一点(我没有在我的视图中有真正的下拉菜单,只是名称,而不是成分的ID)。 你能详细说一下吗? – Fverswijver 2011-04-19 16:35:45

0

如果调用此:

context.People.Add(person); 

你说的EF那个人是必须要插入一个新的实体,而是在同一时间,你是说所有相关实体,其未附上下文也是新的。顺便说一句

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