Saving a list of entities to the db - MVC

asp.net-mvc-3 c# entity-framework

Question

I think I almost have this working, but I cant figure out how to finish.

Model:

 public class Location
 {
    public int LocationId { get; set; }
    public string SiteCode { get; set; }
    public int PersonId { get; set; }
    public int IncidentId { get; set; }
  }

View Model

    public List<Location> LocationList { get; set; }

Controller:

    [HttpPost]
    public ActionResult AddRecord(RecordViewModel model)
    {
        if (ModelState.IsValid)
        {
            Location location;
            foreach (var loc in model.LocationList)
            {
                location = new Location
                {
                    PersonId = model.PersonId,
                    SiteCode = loc.SiteCode,
                    IncidentId = loc.IncidentId
                };
            }

            using (var db = new MyEntities())
            {
                db.Order.AddObject(incident);
                db.Location.AddObject(location);
                db.Comment.AddObject(comment);

                db.SaveChanges();
            }

The line db.Location.AddObject(location); is receiving empty. How do I get the location list from the foreach, to the db?

1
3
6/20/2013 5:42:21 PM

Accepted Answer

You're so close!

// create a new list of your entity Location (may not be in namespace Data)
var locationList = new List<Data.Location>();
foreach (var loc in model.LocationList)
{
    var location = new Data.Location
    {
        PersonId = model.PersonId,
        SiteCode = loc.SiteCode,
        IncidentId = loc.IncidentId
    };
    locationList.Add(location);
}

using (var db = new MyEntities())
{
    db.Order.AddObject(incident);

    foreach (var item in LocationList)
    {
        db.Location.AddObject(location);
    }
    db.Comment.AddObject(comment);

    db.SaveChanges();
}

OR: since you already have the LocationList on your model, use that instead

using (var db = new MyEntities())
{
    db.Order.AddObject(incident);

    foreach (var loc in model.LocationList)
    {
        var location = new Data.Location
        {
            PersonId = model.PersonId,
            SiteCode = loc.SiteCode,
            IncidentId = loc.IncidentId
        };

        db.Location.AddObject(location);
    }
    db.Comment.AddObject(comment);

    db.SaveChanges();
}
5
6/20/2013 5:15:19 PM

Popular Answer

You can simply use addrange.

db.YourTable.AddRange(YourList)
db.SaveChanges();

db.Location.AddRange(LocationList)
db.SaveChanges();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow