基于代码优先类 UserProfile ,使用控制器自动生成编辑操作时出现问题。
public class UserProfile : ApplicationUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string ProfilePhoto { get; set; }
public string Interests { get; set; }
public string AboutMe { get; set; }
public Address Address { get; set; }
public List<Post> Posts { get; set; }
public List<Friends> Friends { get; set; }
public List<Messages> Messages { get; set; }
public List<UsersGallery> UsersGallery { get; set; }
}
UserProfile 与班级地址处于一对一的关系。
public class Address
{
[Key]
public string AddressId { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string HouseOrFlatNumber { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string UserProfileForeignKey { get; set; }
public UserProfile UserProfile { get; set; }
}
FluentApi中描述的关系如下:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<UserProfile>()
.HasOne(p => p.Address)
.WithOne(i => i.UserProfile)
.HasForeignKey<Address>(b => b.UserProfileForeignKey);
}
UserProfile和Address实体是在注册操作
中创建的public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new UserProfile { UserName = model.FirstName, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Address = new Address() };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation("User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
此时,我在UserProfileForeignKey相关的数据库表中有适当的条目。 - UserProfile表 the UserProfile table - 地址表 the Address table
这里出现问题。根据sql错误消息,自动生成的CRUD操作编辑而不是更改地址表中的条目尝试添加具有相同UserProfileForeignKey的新条目。
我理解正确吗?为什么会如此以及如何使“编辑”操作正常工作?
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("FirstName,LastName,BirthDate,ProfilePhoto,Interests,AboutMe,Address,Id,UserName,NormalizedUserName,Email,NormalizedEmail,EmailConfirmed,PasswordHash,SecurityStamp,ConcurrencyStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEnd,LockoutEnabled,AccessFailedCount")] UserProfile userProfile)
{
if (id != userProfile.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(userProfile);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserProfileExists(userProfile.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(userProfile);
}
以下是sql错误消息:
处理请求时发生未处理的异常。
SqlException:无法在对象'dbo.Address'中插入重复的键行 具有唯一索引'IX_Address_UserProfileForeignKey'。
重复键值为(9872561e-dad4-4169-9faf-154c7dcd925f)。声明已经终止。
System.Data.SqlClient.SqlCommand + LT;&GT; c.b__108_0(任务 结果)DbUpdateException:更新时发生错误 条目。有关详细信息,请参阅内部异常。
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch + d__32.MoveNext()
它说ForeignKey 9872561e-dad4-4169-9faf-154c7dcd925f 试图复制,但为什么如果它是更新而不是插入?
答案 0 :(得分:0)
这是因为你的UserProfile实体是分离的(实体框架没有跟踪它),所以它设置了entity.State ==这里添加。 要附加您的实体,请参阅How to Update Existing Disconnected Entity
编辑27/01/2018 我试图复制你的场景,并在GitHub中创建了一个项目https://github.com/updateaman/EF6-Test
在UserProfileForeignKey
对象中设置/传递Address
属性后,我能够摆脱此错误