В ASP.NET Core не удается создать пользователя из-за этой ошибки. Экземпляр типа сущности невозможно отследить, посколькC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 В ASP.NET Core не удается создать пользователя из-за этой ошибки. Экземпляр типа сущности невозможно отследить, поскольк

Сообщение Anonymous »

Пользовательскийконтроллер

Код: Выделить всё

[HttpPost]
[ValidateAntiForgeryToken]
public async Task 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 WMS_User { get; set; }
public DbSet WMS_UserContact { get; set; }
public DbSet WMS_UserDetails { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{

modelBuilder.Entity()
.HasKey(r => r.UserID);
modelBuilder.Entity()
.HasKey(r => r.UserContactID);
modelBuilder.Entity()
.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 Contacts { get; set; } = new List();
}

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 { 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'} уже отслеживается. При присоединении существующих сущностей убедитесь, что присоединен только один экземпляр сущности с заданным значением ключа. В чем причина ошибок в коде?

Подробнее здесь: https://stackoverflow.com/questions/787 ... entity-typ
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»