簡體   English   中英

如何使用實體框架更新字段

[英]How to update a field using Entity Framework

我已經更新了我的問題,以反映以下評論對我的理解。 我的觀點沒有傳遞當前位置的ID,所以這就是它為null的原因。 在我的表格中,我在路線中包含了位置ID。 我更新后的問題是,當我提交表單時,我將如何傳遞路由中返回的ID?

服務層:

public Location GetById(int id)
{
     var location = _context.Locations.Where(l => l.Id == id)
            .Include(l => l.User)
            .FirstOrDefault();

     return location;
}

public async Task UpdateLocationAddress(int locationId, string newAddress)
{
    var location = GetById(locationId);
    location.Address = newAddress;
    await _context.SaveChangesAsync();
}

模型:

public class UpdateLocationModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string PhoneNumber { get; set; }
}

控制器:

public IActionResult Update()
{
    return View();
}

[HttpPost]
public async Task<IActionResult> UpdateLocation(int id, string newAddress)
{
   await _locationService.UpdateLocationAddress(id, newAddress);
   return RedirectToAction("Index", "Location");
}

您單擊地址以轉到表格進行更新的表格:

<table class="table table-hover" id="locationIndexTable">
<thead>
    <tr>
        <th>Name</th>
        <th>Address</th>
        <th>Phone Number</th>
        <th>Delete Location</th>
    </tr>
</thead>
<tbody>
    @foreach (var location in Model.LocationList)
    {
    <tr>
        <td>
            <a asp-controller="Location" asp-action="Detail" asp-route-id="@location.Id">
                @location.Name
            </a>
        </td>
        <td>
            <a asp-controller="Location" asp-action="Update" asp-route-id="@location.Id"> @location.Address</a>
        </td>
        <td>
            @location.PhoneNumber
        </td>
        <td>
            <a class="btn btn-sm btn-primary delete-link">Delete</a>
            <a asp-controller="Location" asp-action="Delete" asp-route-id="@location.Id" class="btn btn-warning btn-sm delete-confirm" style="display:none">Confirm Delete</a>
        </td>
    </tr>
    }
</tbody>
</table>

在表格上查看您更新地址的位置並發布-應該更新地址

@model HealthEval.Models.Location.LocationModel

<h1>Update Location</h1>

<form asp-action="UpdateLocation" method="post" id="updateAddressForm">
    <div class="form-group">
        <label asp-for="Address"></label>
        <input asp-for="Address" class="form-control" />
    </div>
    <button type="submit" id="submitLocationBtn" class="btn btn-submitLocation">Update Location</button>
    <input asp-for="Id" type="hidden" />
</form>

最后是我的錯誤:

NullReferenceException:對象引用未設置為對象的實例。

public async Task UpdateLocationAddress(int locationId, string newAddress)
{
    var location = GetById(locationId);
    location.Address = newAddress; <-- error highlights here
    await _context.SaveChangesAsync();
}

[HttpPost]
public async Task<IActionResult> UpdateLocation(int id, string newAddress)
{
    await _locationService.UpdateLocationAddress(id, newAddress);<--error
    return RedirectToAction("Index", "Location");
}

我可能使此過程過於復雜,因此不勝感激!

LocationModel類

    namespace HealthEval.Models.Location
{
    public class LocationModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string PhoneNumber { get; set; }
    }
}

我認為位置ID是唯一的。

如果位置將始終存在,則在GetLocationById使用Single()而不是FirstOrDefault()

或使用SingleOrDefault()並在以后進行null

在嘗試為不存在的對象分配值之前,請嘗試檢查null。

var location = GetById(locationId);
if(location != null)
{
    location.Address = newAddress; <-- error highlights here
    await _context.SaveChangesAsync();
}

希望有幫助,但您可能還想研究一下GetById方法。

控制器中 ,重命名並將Update() get方法Update()UpdateLocation() ,如下所示:

不要忘記更改Update.cshtml視圖文件名UpdateLocation.cshtml為好。

[HttpGet]
public async Task<IActionResult> UpdateLocation(int id)
{
    Location locationToBeUpdated =  await _locationService.GetById(id);
    return View(locationToBeUpdated);
}

然后在視圖中:

@model Location
<h1>Update Location</h1>

<form asp-action="UpdateLocation" method="post" id="updateAddressForm">
    <div class="form-group">
        <label asp-for="Address"></label>
        <input asp-for="Address" class="form-control" />
    </div>
    <button type="submit" id="submitLocationBtn" class="btn btn-submitLocation">Update Location</button>
    <input asp-for="Id" type="hidden" />
</form>

然后, Controller的 newAddress UpdateLocation()發布方法參數名稱為newAddress但輸入字段名稱為address ,這就是在發布操作期間參數值也newAddress null的原因。 因此,還可以如下修改UpdateLocation() post方法:

[HttpPost]
public async Task<IActionResult> UpdateLocation(int id, string address)
{
   await _locationService.UpdateLocationAddress(id, address);
   return RedirectToAction("Index", "Location");
}

然后在位置服務中

public async Task UpdateLocationAddress(int locationId, string newAddress)
{
    Location locationToBeUpdated = GetById(locationId);
    if(locationToBeUpdated != null)
    {
     locationToBeUpdated .Address = newAddress;
     wait _context.SaveChangesAsync();
    }
}

希望現在它能按預期工作!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM