2017-12-27 171 views
0

我不明白爲什麼這個結果會一直返回null。我知道ID 100存在於數據庫中。我正在創建可以存儲到數據庫中的在線表單。我希望能夠通過ID將他們拉回來更新信息。MVC/Entity Framework編輯動作

public ActionResult reviewPreevent(int? id) 
{ 
    id = 100; 
    if (id.HasValue) 
    { 
     using(formEntities db = new formEntities()) { 
      var form = (from a in db.form_preevent 
       select new preeventForm 
       { 
        id = a.id, 
        meeting = a.meeting, 
        date = (DateTime)a.eventDate, 
        location = a.location, 
        p1Foyer = (bool)a.p1Foyer, 
        p2Foyer = (bool)a.p2Foyer, 
        meetingRoom = (bool)a.meetingroom, 
        skRoom = (bool)a.skroom, 
        kk1 = (bool)a.kk1, 
        kk2 = (bool)a.kk2, 
        nursery = (bool)a.nursery, 
        Sanctuary = (bool)a.sanctuary, 
        kitchen = (bool)a.kitchen, 
        parkingLot = (bool)a.parkinglot, 
        mainLeaders = a.mainleaders, 
        helpers = a.helpers, 
        backup = a.backuphelps, 
        soundboard = (bool)a.soundboard, 
        soundboardtech = a.soundboardtech, 
        projector = (bool)a.projector, 
        projectorOp = a.projectorop, 
        camera = (bool)a.camera, 
        cameraops = a.cameraops, 
        livestream = (bool)a.livestream, 
        ushers = (bool)a.ushers, 
        totalUshers = (int)a.totalushers, 
        greeters = (bool)a.greeters, 
        totalGreeters = (int)a.totalgreeters, 
        security = (bool)a.security, 
        setupTime = (DateTime)a.setuptime, 
        setup = a.setup, 
        breakdown = a.breakdown, 
        foodItems = a.fooditems, 
        groceryShoppers = a.groceryshoppers, 
        foodPrepPersonal = a.foodprep, 
        estExpense = (float)a.estexpense, 
        estIncome = (float)a.estincome, 
        expense = (float)a.expense, 
        income = (float) a.income 
       }).Where(t => t.id == id).FirstOrDefault(); 
      return View(); 
     } 
    }else 
    { 
     TempData["notice"] = "No form with ID: " + id + " was found."; 
     return View(); 
    } 
} 

還有更簡單的方法來匹配一個sql類到viewmodels類嗎?

+0

先構建一個最小查詢:var form = db.form_preevent.FirstOrDefault(x => x.id == 100);看看是否有效。至於你的第二個問題,使用[AutoMapper](http://docs.automapper.org/en/stable/Queryable-Extensions.html)複製所有這些字段。 –

+0

請細化您的問題或標記以下答案之一爲已接受。 –

回答

1

你太親近了。將View返回給客戶端時,必須返回Form變量。

public ActionResult reviewPreevent(int? id) 
{ 
    id = 100; 
    if (id.HasValue) 
    { 
     using(formEntities db = new formEntities()) { 
      var form = (from a in db.form_preevent 
       select new preeventForm 
       { 
        id = a.id, 
        meeting = a.meeting, 
        date = (DateTime)a.eventDate, 
        location = a.location, 
        p1Foyer = (bool)a.p1Foyer, 
        . 
        . 
        . 
        income = (float) a.income 
       }).Where(t => t.id == id).FirstOrDefault(); 
      return View(form); //THIS LINE MODIFIED 
     } 
    }else 
    { 
     TempData["notice"] = "No form with ID: " + id + " was found."; 
     return View(); 
    } 
}