2017-06-06 79 views
1

中的其他表查找值非常新。爲朋友構建一個Tourettes模式跟蹤器。如何從實體框架

我在EF中有兩個相關表。如何在TicEntry表中創建一個具有其他表中的外鍵需求的條目?我將填充TicType,因爲它將保持相當靜態。

用戶需要能夠創建一個理想的TicEntry,只需頻率,嚴重性,TicType選擇。 TicType應該從TicType表中查找。日期有希望是自動的,以及TicEntryID是一個身份。但是,如何在給我的View提供模型時處理TicTypeID?

非常感謝。

public enum Frequency { Low, Medium, High } 
public enum Severity { Low, Medium, High } 
public class TicEntry { 
    public int TicEntryID { get; set; } 
    public int TicTypeID { get; set; } 
    public DateTime DateTime { get; set; } 
    public Frequency? Frequency { get; set; } 
    public Severity? Severity { get; set; } 
    public virtual TicType TicType { get; set; } 
} 

    public enum Type { Motor, Vocal, ComMotor, ComVocal } 
public class TicType 
{ 
    public int TicTypeID { get; set; } 
    public Type? Type { get; set; }   
    public virtual ICollection<TicEntry> TicEntry { get; set; } 
}  

回答

1

讓用戶選擇從Type枚舉抽動類型。然後使用選定的枚舉值從DB中查找TicType條目。

在View.cshtml:

var availableTicTypes = new List<SelectListItem>(
    new SelectListItem{ Value = Type.Motor, Text = "Motor", Selected = true }, 
    new SelectListItem{ Value = Type.Vocal, Text = "Vocal", Selected = false } 
    // ... 
); 
@Html.DropDownListFor(m => m.TickType, availableTicTypes) 

在你的控制器:

var ticType = _dbContext.TicTypes.SingleOrDefault(t => t.Type == viewModel.TickType); 

var tickEntry = new TicEntry { 
    TicType = ticType 
    // set other properties ... 
}; 
_dbContext.TickEntries.Add(tickEntry); 
_dbContext.SaveChanges(); 
+0

謝謝。我會放棄這一點。 – WhatTheDeuce