2013-06-20 32 views
2

我想我幾乎有這個工作,但我不知道如何完成。保存一個實體列表到數據庫 - MVC

型號:

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獲取位置列表?

+0

用'[HttpPost]'裝飾的動作是?另外,什麼是'TrespassEntities'應該是? –

+0

是的它發佈。名稱更改爲MyEntities,它是EF db連接。 – BattlFrog

+0

您應該創建一個回購項目來處理數據庫相關的東西。 – JsonStatham

回答

3

你太親近了!

// 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:既然你已經有了你的模型的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(); 
} 
+0

謝謝大衛,就是這樣。 – BattlFrog

0

您可以簡單地使用的AddRange。

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

db.Location.AddRange(LocationList) 
db.SaveChanges(); 
相關問題