Reputation: 143
very new to this. Building a Tourettes pattern tracker for a friend.
I have two related tables in EF. How can I create an entry in the TicEntry table that has a foreign key requirment from the other table? I will populate TicType as it will remain pretty static.
A user needs to be able to create an TicEntry ideally with just Frequency, Severity, TicType selections. TicType should lookup from the TicType Table. Date will hopefully be auto, as well as TicEntryID which is an IDENTITY. But how do I deal with the TicTypeID when giving a model to my View?
Many thanks.
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; }
}
Upvotes: 2
Views: 275
Reputation: 9463
Let the user select the tic type from the Type
enum. Then use the selected enum value to look up the TicType entry from the DB.
In the 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)
In your Controller:
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();
Upvotes: 1