BattlFrog
BattlFrog

Reputation: 3397

Saving a list of entities to the db - MVC

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?

Upvotes: 4

Views: 11926

Answers (2)

Ellix4u
Ellix4u

Reputation: 586

You can simply use addrange.

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

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

Upvotes: 0

David L
David L

Reputation: 33815

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

Upvotes: 5

Related Questions