Cześć
ostatnio miałem problem z pobieraniem danych (dziękuję za pomoc przy ogarnięciu tematu),
a teraz nie radzę sobie z dodawaniem nowego rekordu do tabeli korzystając z Entity Framework.
Struktura tabelek wygląda tak:
public class User
{
[Key]
[Column(TypeName = "uniqueidentifier")]
[Required]
public Guid UserID { get; set; }
[Column(TypeName = "nvarchar(100)")]
[Required]
public string UserName { get; set; }
public ICollection<Ticket> Tickets { get; set; }
public ICollection<Message> Messages { get; set; }
}
public class Message
{
[Key]
[Column(TypeName = "uniqueidentifier")]
[Required]
public Guid MessageID { get; set; }
[Required]
public Guid TicketID { get; set; }
[Column(TypeName = "uniqueidentifier")]
[Required]
public Guid OwnerID { get; set; }
[Column(TypeName = "nvarchar(max)")]
[Required]
public string Information { get; set; }
public Ticket Ticket { get; set; }
public User User { get; set; }
}
public class Ticket
{
[Key]
[Column(TypeName = "uniqueidentifier")]
[Required]
public Guid TicketID { get; set; }
[Column(TypeName = "uniqueidentifier")]
[Required]
public Guid OwnerID { get; set; }
public User User { get; set; }
public ICollection<Message> Messages { get; set; }
}
Korzystam z relacji między tabelami:
- W tabeli "Ticket" mam wpisy których właściciel jest w tabeli "User".
- Każdy wpis może mieć wiele wiadomości (tabela "Message") napisanych przez różne osoby, które również są w tabeli "User".
Z wyciąganiem danych nie mam już problemu, ale teraz chciałbym dodać nowy rekord do tabeli "Message". Próbowałem to zrobić w taki sposób:
_dbContext.Messages.Add(message);
await _dbContext.SaveChangesAsync();
Niestety mam błąd:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'UserID'.
Pomyślałem, że w takim razie spróbuję zrobić to idąc przez tabelę "User". Kombinowałem coś w rodzaju:
_dbContext.Users.Where(p => p.UserID == userID).Include(p => p.Messages).FirstOrDefault().Messages.Add(message);
await _dbContext.SaveChangesAsync();
Jednak tym razem mam błąd:
Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'UserID'.
Invalid column name 'UserID'.
Bedę wdzięczny za wskazówki jak to rozwiązać i prawidłowo dodać rekord do tabeli "Message".
Dzięki i pozdrawiam :)