C# ASP.NET一对一关系CRUD
控制器根据代码第一类用户配置文件自动生成的编辑操作有问题C# ASP.NET一对一关系CRUD,c#,asp.net,entity-framework,C#,Asp.net,Entity Framework,控制器根据代码第一类用户配置文件自动生成的编辑操作有问题 public class UserProfile : ApplicationUser { public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } public string ProfilePhot
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; }
}
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);
}
模型创建时受保护的覆盖无效(ModelBuilder)
{
基于模型创建(生成器);
builder.Entity()
.HasOne(p=>p.Address)
.WithOne(i=>i.UserProfile)
HasForeignKey先生
-地址表
这里出现了一个问题。根据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);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务编辑(字符串id、[Bind(“FirstName、LastName、BirthDate、ProfilePhoto、interest、AboutMe、Address、id、UserName、NormalizedEmail、emailconfirm、PasswordHash、SecurityStamp、ConcurrencyStamp、PhoneNumber、phonenumberconfirfied、twofacturenabled、LockoutEnd、LockoutEnabled、AccessFailedCount”)]用户配置文件用户配置文件用户配置文件用户配置文件
{
if(id!=userProfile.id)
{
返回NotFound();
}
if(ModelState.IsValid)
{
尝试
{
_更新(userProfile);
wait_context.SaveChangesAsync();
}
catch(DbUpdateConcurrencyException)
{
如果(!userProfile存在(userProfile.Id))
{
返回NotFound();
}
其他的
{
投掷;
}
}
返回重定向到操作(名称(索引));
}
返回视图(userProfile);
}
以下是sql错误消息:
处理请求时发生未处理的异常
SqlException:无法在对象“dbo.Address”中插入重复的键行
具有唯一索引“IX_Address_UserProfileForeignKey”
重复的键值为(9872561e-dad4-4169-9faf-154c7dcd925f)。语句已终止
System.Data.SqlClient.SqlCommand+c.b_uu108_u0(任务
结果)DbUpdateException:更新数据库时出错
条目。有关详细信息,请参阅内部异常
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch+d__32.MoveNext()
它说ForeignKey 9872561e-dad4-4169-9faf-154c7dcd925f试图被复制,但如果它是一个更新而不是一个插入,为什么呢?这是因为用户配置文件实体被分离(实体框架没有跟踪它),所以它设置了实体。状态==添加到这里。
要附加您的实体,请参见
编辑2018年1月27日
我试图复制您的场景,并在GitHub中创建了一个项目
在Address
对象中设置/传递UserProfileForeignKey
属性后,我能够消除此错误设置子对象(地址)的实体状态,如Aman所示,或者将其带入跟踪(然后将更改映射回)。谢谢,但您能提供更多详细信息吗?附件应该是什么样子以及应该放在哪里?我试过这样做:\u context.Address.Attach(userProfile.Address);
`u context.Entry(userProfile.State=EntityState.Modified;`wait\u context.savechangesync();
如下:\u context.UserProfile.Attach(UserProfile);\u context.Entry(UserProfile.State=EntityState.Modified;
wait\u context.SaveChangesAsync()
关于复制仍然是相同的sql错误我看到您正在传递userProfile的Id而不是Address的addressId,传递/设置addressId并重试谢谢您,我真的很感谢您的帮助。如果您是指绑定,我已经尝试了与addressId一起使用,但它不起作用。公共异步任务编辑(字符串Id,[绑定("名字,姓氏,出生日期,个人资料照片,兴趣,关于我,地址。地址Id,地址。城市,地址。街道,地址。房屋或公寓号码,地址。邮政编码,地址。国家,Id,用户名,标准化用户名,电子邮件,标准化邮件,电子邮件确认,密码哈希,安全戳,并发处理,电话号码,电话号码确认,双因素编码,锁定输出,锁定输出已启用,AccessFailedCount“]UserProfile UserProfile)
错误消息已更改,但是:\uuuu\ DbUpdateConcurrencyException:数据库操作预期影响1行,但实际影响0行。自加载实体后,数据可能已被修改或删除。有关理解和处理乐观并发异常的信息,请参阅。很好。请求中是否有AddressId?是否在userProfile.Address.AddressId中看到任何值?
[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);
}