0

UserController

[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);
}

Model

 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; }
}

Hello everyone, In the creation of user i encountering an error on this part _context.WMS_UserDetails.Add(userDetails); saying System.InvalidOperationException: 'The instance of entity type 'UserDetails' cannot be tracked because another instance with the same key value for {'UserID'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. What are the reason what's wrong in code?

3
  • Have you tried this? Commented Jul 24, 2024 at 17:38
  • @TP95 Not yet, How to use this services.AddScoped<> what value inside in addscoped? Commented Jul 24, 2024 at 17:52
  • looks like you're using a string as primary key for UserDetails. Not sure why you do that... all those relationships should be made on primary keys, and let the DB make those. When adding a new model object to DB the primary key should be null... after it has been added, the primary key will be created (INT). Then read that value and use that for any foreign keys. (Just reading last one and ++ is not a good idea as it's not guaranteed to be unique... only the DB can guarantee that...) Not real sure if that's the cause of the error, though. User is also missing a primary key? Commented Jul 24, 2024 at 20:26

1 Answer 1

0

After testing your code, I found that the cause of this problem is that two entity instances with the same primary key are tracked in the same context. Since you used = new UserDetails(); when configuring the navigation property of UserDetails in the User model, this will cause the UserDetails property to be automatically initialized to a new UserDetails object whenever a new User instance is created, and the UserDetails instance is repeatedly referenced in the Create method. Therefore, you can configure UserDetails in the model as:

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>();
}

When inserting related data: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.