在具有以下(简化)模型的ASP.NET MVC5应用程序中:
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CustomerID { get; set; }
public string Name { get; set; }
public string PrimaryContact { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public Reseller Reseller { get; set; }
}
public class Reseller
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CompanyId { get; set; }
public ICollection<Customer> Customers { get; set; }
}
我希望能够更新与客户关联的经销商。当尝试通过将客户实体标记为已修改(ctx.Entry(customer).State = EntityState.Modified
)来更新Customer实体时,所有列均会更新,但经销商的CompanyID除外。据我了解,Modified
将所有字段标记为肮脏并更新所有字段,但这在这里没有发生。
以下是用于更新客户的控制器操作。我已经检查并在传入模型中正确设置了转销商的正确CompanyID:
[HttpPost]
public ActionResult Edit(Customer customer)
{
if (ModelState.IsValid)
{
using (var ctx = new DbContext())
{
ctx.Entry(customer).State = EntityState.Modified;
ctx.SaveChanges();
return RedirectToAction("Info", new { id = customer.CustomerID });
}
}
return View(customer);
}
调用SaveChanges时,将生成以下SQL。请注意,转销商公司ID不包含在查询中:
UPDATE [dbo].[Customer]
SET [Name] = @0, [PrimaryContact] = @1, [Email] = @2, [PhoneNumber] = @3
WHERE ([CustomerID] = @4)
-- @0: 'Sample Customer iuhiuhi' (Type = String, Size = -1)
-- @1: 'Joe Bloggs' (Type = String, Size = -1)
-- @2: 'example@example.com' (Type = String, Size = -1)
-- @3: '123456789' (Type = String, Size = -1)
-- @4: 'e4b9e8d3-9f92-e811-baa4-3052cb3d0eb2' (Type = Guid)
即使它是客户实体的一部分。
答案 0 :(得分:1)
将ResellerId添加到客户模型
{
"python.pythonPath": "src/.venv/bin/python",
"python.testing.nosetestsEnabled": false,
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"python.testing.pytestArgs": [
"src",
"-s"
],
"python.linting.enabled": true,
"autoDocstring.docstringFormat": "google"
}
然后更改ResellerId