Nella mia app sto utilizzando EF Core per definire 2 entità (Code First), Meeting
e PostcodeDetail
definite come segue:
public class Meeting
{
public int Id { get; set;}
public PostcodeDetail PostcodeDetail { get; set; }
// other properties removed for brevity
}
public class PostcodeDetail
{
public int Id { get; set; }
public ICollection<Meeting> Meetings { get; set; } = new List<Meeting>();
// other properties removed for brevity
}
Quando creo una nuova Meeting
e provo ad assegnare un'entità PostcodeDetail
esistente come segue:
var meeting = new Meeting();
var details = context.PostcodeDetails
.SingleOrDefault(i => i.Prefix == prefix);
meeting.PostcodeDetail = details;
context.SaveChanges();
Ottengo questa eccezione:
Microsoft.EntityFrameworkCore.DbUpdateException: SqlException: impossibile inserire il valore esplicito per la colonna Identity nella tabella 'PostcodeDetail' quando IDENTITY_INSERT è impostato su OFF
Non riesco a capire perché un'espressione di inserimento sia in esecuzione su PostcodeDetail
, poiché sto recuperando un'entità esistente dal database: qualcuno può vedere cosa sto facendo male qui?
Modifica: quando eseguo SQL Server Profiler posso vedere quanto segue viene eseguito
INSERISCI IN [PostcodeDetail] ([Id], [DateCreated], [DateModified], [District], [Prefix], [Region]) VALUES (@ p0, @ p1, @ p2, @ p3, @ p4, @ p5) ; ', N' @ p0 int, @ p1 datetime2 (7), @ p2 datetime2 (7), @ p3 nvarchar (4000), @ p4 nvarchar (4000), @ p5 nvarchar (4000) ', @ p0 = 113, @ p1 = '2019-01-02 15: 50: 49.5874691', @ p2 = '2019-01-02 15: 50: 49.5874640', @ p3 = N'Guernsey ', @ p4 = N'GY', @ p5 = Isole N'Channel '
Non so perché viene generato un inserto, poiché sto recuperando PostcodeDetail dal database e facendo riferimento alla nuova Meeting
La causa di questo problema era che chiamavo SaveChanges
in un contesto diverso rispetto al contesto con cui stavo creando l'entità.
potrebbe essere che si sta tentando di assegnare un valore esplicitamente a una colonna in cui il database lo assegna automaticamente. oppure hai creato un campo PK non identico su un tavolo. Puoi impostarlo così
oppure puoi farlo anche con i campi identità:
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }