2011-04-19 58 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;