将实体列表保存到db-MVC

时间:2013-06-20 16:57:28

标签: c# asp.net-mvc-3 entity-framework

我想我几乎有这个工作,但我无法弄清楚如何完成。

型号:

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

查看模型

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

控制器:

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

db.Location.AddObject(location);收到空。如何从foreach获取位置列表到db?

2 个答案:

答案 0 :(得分:4)

你真是太近了!

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

或者:因为您已经在模型上有了LocationList,所以请改用

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

答案 1 :(得分:0)

您只需使用addrange。

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

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