开发者

C# EntityFramework saving 1-1 relation

I have a one-to-one relationship between the Employee and EmployeePermission entities with navigation properties PermissionTo and Employee respectively. I can load the navigation properties fine, but the problem I'm having is that when I change properties on the related entity EmployeePermission, attach the Employee entity to a database context and call the SaveChanges() method, the changes in the EmployeePermission entity are not being persisted to the database, but the changes in the Employee entity are.

Here's what my model looks like:

C# EntityFramework saving 1-1 relation

Here's what my save function looks like:

public static void SaveEntities(List<TEntity> entities)
{
    using(var db = GetContext())
    {
        ObjectSet<TEntity> table = db.CreateObjectSet<TEntity>();
        foreach(TEntity entity in entities)
        {
            if (entity.IsNew())
                table.AddObject(entity);
            else
            {
                table.Attach(entity);
                EntityState state = (entity.EntityKey.IsTemporary) ? EntityState.Added : EntityState.Modified;
                table.Context.ObjectStateManager.ChangeObjectState(entity, state);
            }
        }
        db.SaveChanges();
    }
}

IsNew() is an extension method I added to the EntityObject class to check if the Entity has to be added or attached to the EntitySet.

/// <summary>
/// Returns a value indicating if the entity object is new.
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public static bool IsNew(this EntityObject entity)
{
    return (entity.EntityKey == null || entity.EntityKey.IsTemporary);
}

I load an employee and bind its properties on a form, change them and call the SaveEntities() method. All the changes to the Employee entity are saved to the database, but the changes to the EmployeePermission entity are not saved to the database, and I haven't gotten to the other entities yet.

I'm not sure what I'm doing wrong and have been searching for hours. I appreciate all the help, th开发者_开发技巧anks in advance.


Doesn't sound like you've changed the EmployeePermission record since you added it to the context. Since the EF doesn't know it's modified, it's unaware there's anything to save. You can call ChangeObjectState on that object, as well, if you care to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜