我定义了以下实体:
public class Customer
{
public int CustomerId { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string PhoneNumber { get; set; }
[Required]
public string Email { get; set; }
public ICollection<Call> Calls { get; set; }
}
我正在尝试在控制器方法中更新实体的字段:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("CustomerId,FirstName,LastName,PhoneNumber,Email")] Customer customer)
{
if (ModelState.IsValid)
{
_context.Update(customer);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(customer);
}
private readonly CustomerContext _context;
模型的所有值在视图中都已更改,并已正确传递给方法。 ModelState
有效。所有方法都已执行,但毕竟在数据库中只更改了FirstName
和LastName
。其他属性没有。我检查了执行的SQL:
UPDATE [Customers] SET [FirstName] = @p0, [LastName] = @p1
WHERE [CustomerId] = @p2;
为什么不更新其他属性?
查看代码:
<h4>Customer</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="CustomerId" />
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PhoneNumber" class="control-label"></label>
<input asp-for="PhoneNumber" class="form-control" />
<span asp-validation-for="PhoneNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</form>
</div>
</div>
CustomerContext.cs
public class CustomerContext : DbContext
{
public CustomerContext(DbContextOptions<CustomerContext> options): base(options){ }
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().HasAlternateKey(cu => cu.PhoneNumber);
modelBuilder.Entity<Customer>().HasAlternateKey(cu => cu.Email);
}
}
答案 0 :(得分:0)
原来问题的根源是备用键列,因为省略了键。我删除了它们并用索引替换它们,一切正常。
modelBuilder.Entity<Customer>().HasIndex(cu => cu.PhoneNumber).IsUnique();
modelBuilder.Entity<Customer>().HasIndex(cu => cu.Email).IsUnique();