In an ASP.NET MVC application using entity framework, I have an Edit view where I am updating some properties on one of my entity models. I'd like to put an "add" button for one of the properties if the user wants to add a new property of that type (but without deleting the older entry, I understand this requires a List of those type of properties). When I click this add button, using Ajax.ActionLink
will retrieve a new Html.EditorFor
helper from a partial view and add it to the current form.
Currently my ActionMethod looks like it's only updating the fields that are already there, what kind of logic can I add to say "if this is a new property, then db.Add"?
heres what my method looks like now:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TimeSeriesData(List<TimeSeriesData> List1)
{
int empid = List1[0].EmployeeID;
if (ModelState.IsValid)
{
foreach (TimeSeriesData ln in List1)
{
db.Entry(ln).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Edit", new { id = empid });
}
return new EmptyResult();
}
I'd like to add logic somewhere inside the foreach loop and say if the item in the list is a new item, then db.MyModel.List.Add(item);
but I'm not sure how to check if the list item is new
would it be something like
if (newproperty.propertyid == null) {
db.MyModel.List.Add(newproperty);
}
Please let me know if you need more clarification
EDIT
Or another way to ask my question is: how can I check if the item already exists in the database,
models:
//summarized
class Employee {
int EmployeeID {get;set;}
List<TimeSeriesData> TimeSeriesData {get;set;}
}
class TimeSeriesData {
int TimeSeriesDataID {get; set;}
int EmployeeID {get;set;}
string Value {get;set;}
[ForeignKey("EmployeeID")]
public Employee Employee { get; set; }
}