C
C#2y ago
Elio

❔ Entity Framwork SQLite Add

Hello, i've a little problem there. I'm trying to add something new in my database but i do not understand why it works in the case 1 and not in the case 2. case 1 : i add a new material to the database passing only the name and MaterialTypeId
new Material(_viewmodel.Name, _viewmodel.MaterialType.Id) case 2: i add a new material to the database passing the name and MaterialType but there it show me the error SQL error 19 Unique Id failed new Material(_viewmodel.Name, _viewmodel.MaterialType) Have you any idea what am i doing wrond ?
9 Replies
Angius
Angius2y ago
Trying to add an entity that has an unattached child entity will try to create both the parent entity and the child entity And since it has an ID that probably already exists, it fails
Elio
ElioOP2y ago
ohh ok so the good way to add a new material there i to fill only the materialTypeId and not the entity that's right ?
Angius
Angius2y ago
Yep
Elio
ElioOP2y ago
perfect i was a bit lost ahah you saved me thanks !
FusedQyou
FusedQyou2y ago
You can also create the material type first, add that to the database using context.Add() and then create the material, referencing the material type you just added. EntityFramework will fill in the Id for you. You only need to save after adding the material. No need to do it when adding the material type It's a bit weird, but EntityFramework wraps your class into something it can track, so context.Add() will fix your issue because it will start tracking it.
Angius
Angius2y ago
Or, if you have an existing entity that's not tracked for some reason, you can force tracking with context.Attach(theThing) Avoid it tho
FusedQyou
FusedQyou2y ago
Yup But filling in the ID also works perfectly. The only drawback is that you need to save your changes first for EF to give your material type an ID at all, so this takes two saves
Elio
ElioOP2y ago
yup but it's fine to me cause i will never create a materialType and a material at the same moment so i will do it separately every time thanks for the precision 🙂
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server