Access Context/other EntityObjects from partial class

559 views Asked by At

I need to add a new EntityObject to Context when one specific (calculated) property is changed in another EntityObject. There seems to be no access to Context from any EntityObject itself.

For example, my "Employee" partial class has a custom property:

Public Property Age As Integer
      Get
          Return _Age
      End If
      End Get
      Set(value As Integer)
          'Here based on some conditions, I sometimes need to add a new 
          'EntityObject to (or modify an existing EntityObject) in an EntitySet "Assumptions"
          'HOW TO DO THAT ?

         _Age=value
      End Set
End Property
Private _Age as Integer

...and when the above "Age" is set, I sometimes need to create and add one new EntityObject "Assumption" to the "Assumptions" EntitySet which is under the same Context.

I know that is not good design to access EntityObjects from another EntityObjects like that but how can I solve this need in any other way?

1

There are 1 answers

0
Joe Brunscheon On

Add another class to your solution that is a partial class of your EntityObject that you are doing this with.

Add a property to that class:

public partial class EntityObject
{
    private int _age;
    public List<Assumption> Assumptions { get; set; }
    public int Age
    {
        get { return _age; }
        set { _age = value; Assumptions.Add(new Assumption("Age", value); }
    }
}

When you use EF to query the EntityObject class, you need to "Include" the navigational property in your query.

var db = new DatabaseContext();
var myObjects = db.EntityObjects.Include("Assumption").Where(....).ToList();

That should get you what you need. Then you can encapsulate your logic to modify any Assumptions as needed.