Search code examples
c#asp.netasp.net-mvcentity-framework

controller action method to update and add properties to database


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; }
}

Solution

  • There's a problem within your code structure. If you will notice,

     db.Entry(ln).State = EntityState.Modified;
    

    you are just updating/editing that specific entity and not adding a property. And also, I assume that you kinda missed out some logic.

    If you're going to add another property for it, you should put it in a separate table and reference it to the primary key of the parent table. By this, you will not have any problem adding another value for that.

    To answer your second question, you can use .Any property of the context to check out if the item exists in the database. You can have something like this:

    var db = new Context();
    if(!db.mytable.Any(m => m.field == value)){
        db.mytable.Add(value);
        db.SaveChanges();
    }
    

    Should you have any question, please feel free to ask.