Adding a child entity to parent entityset

2019-09-14 21:12发布

问题:

Wondering if there is a good way(generic method which is) that can dynamically add child entity to appropriate entity set of a parent. Right now I have to do something like this, and it's not very elegant:

 public int AppendChild<T>(PATIENT patient, T child)
    where T : EntityBase

  switch (typeof(T).Name)
  {               
     case "EYE_EXAM":
          patient.EYE_EXAMS.Add((EYE_EXAM)child);
          break;

     case "LEGS_EXAM":
          patient.LEGS_EXAMS.Add(LEGS_EXAM)child);
          break;

     //etc, a very long list of possible types goes here

  }

Is there better way to do this? Thanks for answers

回答1:

public void CreateChildIfNull<T>()
{
    var child = Activator.CreateInstance(typeof(T));
    Entity.GetType().GetProperty(typeof(T).Name).SetValue(patient, child , null);
}

or

    public void CreateChildIfNull(LambdaExpression Child)
    {
        Type ChildType = Child.Body.Type;
        var myvar = Activator.CreateInstance(ChildType);
        Entity.GetType().GetProperty(ChildType.Name).SetValue(Entity, myvar, null);
    }


标签: linq-to-sql