views:

48

answers:

2

I am implementing the entity framework for the first time. I am working with adding/updating objects that have a parent property.

I am aware that the parent entity of an entity is initialized as "null". I do not have a full understanding of how to use the parent entity vs. the parent entity reference fields, or what is required to be able to save the changes to an entity.

  1. Am I missing any important factors in my analysis (i.e. EntityState?)
  2. Which of the following situations are possible, and
  3. What is the best method for dealing with them:

Entity: null
EntityReference: not null

Entity: not null
EntityReference: null

Entity: not null
EntityReference: not null

Thank you for any help.

code sample:

internal void AddUpdateObject(MyDataContext context)
{
// HOW DO I HANDLE THIS SECTION vvvv
if (this.MyParentEntity == null)
{
    throw new Exception("Parent Property Null.");
}
if (this.MyParentEntity.EntityState == EntityState.Detached)
{
    MyParentEntity t = this.MyParentEntity;
    this.MyParentEntity = null;
    context.AttachTo("ParentCollection", t);
    this.MyParentEntity = t;
}
// ^^^^^^^^^
try
{
    context.AddToMyEntities(this);
}
catch (InvalidOperationException)
{
    // the object with the key already exists
    MyEntity ent = context.MyEntities.First(x => x.id == this.id);
    PropertyInfo[] props = typeof(MyEntity).GetProperties();
    foreach (PropertyInfo pi in props)
    {
        if (pi.CanRead && pi.CanWrite &&
            !pi.PropertyType.Name.StartsWith("EntityCollection") &&
            !pi.Name.Equals("id"))
            pi.SetValue(ent, pi.GetValue(this, null), null);
    }
}
}
A: 

You could do something like:

var entity = context.MyEntities.FirstOrDefault(x => x.id == this.id);
if (entity != null)
{
    // updating
    // HOW DO I HANDLE THIS SECTION vvvv
    if (!entity.MyParentEntityReference.IsLoaded)
    {
        entity.MyParentEntityReference.Load();
    }
}
else
{
    // inserting
    entity = this;
    context.AddToMyEntities(this);
    this.ParentEntity = // whatever
}
entity.SomeOtherProperty = someValue;
context.SaveChanges();

Does that answer your question?

Craig Stuntz
A: 

This is what worked:

MyEntity e = context.MyEntities.FirstOrDefault(x => x.id == this.id);
if(e == null){
    MyParent p = this.Parent;
    this.Parent = null;
    context.Attach(p);
    this.Parent = p;
}
else
{
    context.ApplyPropertyChanges("MyEntities", this);
}

Some reference links:
ApplyPropertyChanges
Adding objects with references to other objects

Sako73