2017-06-06 90 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