用户控制器
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CreateUserDetailsForm createUser)
{
try
{
// Generate a unique UserID
var lastUserId = GetLastUserId(); // Implement this method to fetch the last ID
int newID = Convert.ToInt32(lastUserId);
newID++;
createUser.UserID = newID.ToString();
createUser.CreatedDate = DateTime.Now;
createUser.ModifiedBy = "SYSTEM";
createUser.ModifiedDate = DateTime.Now;
// Save data to WMS_User table
var user = new User
{
UserID = createUser.UserID,
Password = createUser.Password,
Role = createUser.Role,
Status = "1", //Active
CreatedDate = createUser.CreatedDate,
ModifiedBy = createUser.ModifiedBy,
ModifiedDate = createUser.ModifiedDate
};
_context.WMS_User.Add(user);
var userDetails = new UserDetails
{
UserID = createUser.UserID,
FirstName = createUser.FirstName,
MiddleName = createUser.MiddleName,
LastName = createUser.LastName,
Email = createUser.Email,
CreatedDate = createUser.CreatedDate,
ModifiedBy = createUser.ModifiedBy,
ModifiedDate = createUser.ModifiedDate,
};
_context.WMS_UserDetails.Add(userDetails);
var lastContactId = GetLastContactId(); // Implement this method to fetch the last ID
int newContact = Convert.ToInt32(lastContactId);
// Save data to WMS_UserContact table (assuming each user can have multiple contacts)
foreach (var contact in createUser.CreateContactDetails)
{
newContact++;
var userContact = new UserContact
{
UserContactID = newContact.ToString(),
UserID = createUser.UserID,
ContactType = contact.ContactType,
ContactNumber = contact.ContactNumber,
CreationDate = createUser.CreatedDate,
ModifiedBy = createUser.ModifiedBy,
ModifiedDate = createUser.ModifiedDate
};
_context.WMS_UserContact.Add(userContact);
}
await _context.SaveChangesAsync();
TempData["SuccessMessage"] = "Resident registered successfully.";
return RedirectToAction("Manage", "User");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating user: {Message}", ex.Message);
TempData["ErrorMessage"] = "Unable to create user. Please try again.";
// Error: Redirect to Manage with error message
return RedirectToAction("Manage", "User");
}
}
ApplicationDbContext.cs
public DbSet<User> WMS_User { get; set; }
public DbSet<UserContact> WMS_UserContact { get; set; }
public DbSet<UserDetails> WMS_UserDetails { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasKey(r => r.UserID);
modelBuilder.Entity<UserContact>()
.HasKey(r => r.UserContactID);
modelBuilder.Entity<User>()
.HasMany(r => r.Contacts)
.WithOne(a => a.User)
.HasForeignKey(a => a.UserID);
}
型号
public class User
{
public string UserID { get; set; }
public string Password { get; set; }
public string Role { get; set; }
public string Status { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDate { get; set; }
// Navigation properties
public UserDetails UserDetails { get; set; } = new UserDetails();
public ICollection<UserContact> Contacts { get; set; } = new List<UserContact>();
}
public class UserDetails
{
[Key]
public string UserID { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDate { get; set; }
public User User { get; set; }
}
public class UserContact
{
[Key]
public string UserContactID { get; set; }
public string UserID { get; set; }
public string ContactType { get; set; }
public string ContactNumber { get; set; }
public DateTime CreationDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDate { get; set; }
public User User { get; set; }
}
public class CreateUserDetailsForm
{
public string UserID { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Role { get; set; }
public List<CreateContactDetails> CreateContactDetails { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDate { get; set; }
}
大家好,在创建用户时我遇到了这部分的错误 _context.WMS_UserDetails.Add(userDetails);说 System.InvalidOperationException:“无法跟踪实体类型“UserDetails”的实例,因为已跟踪具有相同 {'UserID'} 键值的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。代码出错的原因是什么?
测试您的代码后,我发现此问题的原因是在同一上下文中跟踪具有相同主键的两个实体实例。由于您在 User 模型中配置 UserDetails 的导航属性时使用了
= new UserDetails();
,这将导致每当创建新的 User 实例时,UserDetails 属性都会自动初始化为新的 UserDetails 对象,并且在 UserDetails 实例中重复引用 UserDetails 实例。创建方法。因此,您可以在模型中将 UserDetails 配置为:
public class User
{
public string UserID { get; set; }
public string Password { get; set; }
public string Role { get; set; }
public string Status { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDate { get; set; }
public UserDetails UserDetails { get; set; }
public ICollection<UserContact> Contacts { get; set; } = new List<UserContact>();
}