I use EF 5 and Code First.
Ive got a main ViewModel that exposes a Translation Property. A Translation consists out of 1 to n Translation Items. The Translation Property is bound to a Usercontrol. When the Translation is created and Added via _context.Translations.Add(t) in the Viewmodel also all TranslationItems inside the Translation are saved and stored correctly in the DB.
But when i try to Add a new TranslationItem (t.TranslationItems.Add) to a existing Translation it isn’t saved in the DB. context.ObjectStateManager.GetObjectStateEntries(EntityState.Added) also returns no elements so i guess the new Translation Items is still unattached. Since the TranslationItem is added inside the Child Usercontrol, i can’t access the current Datacontext To set the Entity State to Added.
What can i do?
Edit:
public class Translation : BaseEntity, IValidatableObject
{
private List<TranslationItem> _translations;
public virtual List<TranslationItem> Translations
{
get{
return _translations;
}
set
{
_translations = value;
}
}s
In ViewModel:
Translation = new Translation(); or
Translation = repo.GetTranslation(1);
Binding to custom Usercontrol:
<Views:TranslationTextInput Translations="{Binding Translation}"/>
In code behind of UserControl:
Trans.Translations.Add(new TranslationItem() { Text = "", Lcid = new CultureInfo("en").LCID });
Save function:
public void Update(Translation t)
{
if (t.Id == 0)
_context.Units.Add(t);
_context.SaveChanges();
}
I create the Context in the Viewmodel Constructor and pass it to the repository class.
The ChangeTracker should automatically grab all it’s children if the
Translationis properly attached. However, you could try attaching all of theTranslationItemsinside theTranslationif you’re sure that theTranslationis attached to the context.I’m not sure of the
DbSetname forTranslationItems, change that to whatever you named it.