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.
- Am I missing any important factors in my analysis (i.e. EntityState?)
- Which of the following situations are possible, and
- 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);
}
}
}