Entity Framework Problema EntityKey / Chiave esterna
-
06-07-2019 - |
Domanda
Come risultato di un post di un modulo, sto cercando di salvare un nuovo record del marchio. A mio avviso, Gender è un menu a discesa che restituisce un numero intero, che viene popolato da ViewData (" gender ")
Ho impostato il mio link come segue:
gID = CInt(Request.Form("Gender"))
Brand.GenderReference.EntityKey = New EntityKey("DB_ENTITIES.Gender", "Id", gID)
TryUpdateModel(Brand)
DB.SaveChanges()
Che provoca il seguente errore.
Entities in 'DB_ENTITIES.Brand' participate in the 'FK_Brand_Gender' relationship. 0 related 'Gender' were found. 1 'Gender' is expected.
Qualcuno potrebbe spiegarmi i parametri in un inglese semplice. Ho anche provato DB.Gender come primo parametro ma nessuna gioia.
Soluzione
Invece di creare un EntityKey, crea un oggetto Gender stub (mi dispiace non sono un ragazzo VB, quindi in C #):
Gender g = new Gender{ID = Int32.Parse(Request.Form("Gender"))};
Quindi si collega il genere al EntitySet
appropriato (il nome della proprietà su DB
da cui si ottengono le entità di genere è la stringa seguente):
DB.AttachTo("Genders",g);
In questo modo il database si trova nello stato in cui Gender si trova in ObjectContext
nello stato invariato senza una query del database. Ora puoi costruire una relazione come di consueto
brand.Gender = g;
DB.AddToBrand(brand);
DB.SaveChanges();
Questo è tutto ciò che c'è da fare. Non c'è bisogno di scherzare con EntityKeys
Spero che questo aiuti
Altri suggerimenti
Ciò di cui hai bisogno è un'istanza di Brand e Gender, quindi imposta Brand.Gender sull'istanza di Gender. Quindi puoi salvare senza problemi.
Ok, ecco cosa ho inventato invece di usare updateModel. Sembra essere problematico / potenzialmente un rischio per la sicurezza con l'aggiunta di campi potenzialmente aggiuntivi nel post. Una nuova istanza di Gender può essere istanziata tramite trygetObjectByKey. Questo sta funzionando finora. Altri suggerimenti su come ottenere UpdateModel per aggiornare l'oggetto della proprietà Gender sono apprezzati.
Dim cID As Integer
cID = CInt(Request.Form("Gender"))
Dim key As New EntityKey(DB.DefaultContainerName() & ".Gender", "ID", cID)
Dim objGenderDS As New Gender
'Bring back the Gender object.
If DB.TryGetObjectByKey(key, objGenderDS) Then
Brand.GenderReference.EntityKey = key
Brand.Gender = objGenderDS
DB.AddToBrand(Brand)
DB.SaveChanges()
Else
End If