mercredi 13 septembre 2017

Check if an attached object have any related data base on navigation property

I was try to create a function that could detect if one attached object have related data in different table. I expect to the action avoid cascade delete but warn the user manually remove the children instead. It has to be dynamic and each navigation property is also unknown type.

My problem is when I selecting the value return by Property.GetValue(), it is boxed and the collection is also dynamic, therefore I can't count the collection hence do the relevant checking. Thus my question is how can I cast object convert to ICollection refer to the dynamic type in Linq method?

I was spending one whole day and couldn't get an answer, maybe it is my misunderstanding of the EF concept but please help, many thanks!

    //Domain Model
public class Course
{
    [Key]
    public int CourseID { get; set; }

    [ForeignKey("CourseID")]
    public virtual ICollection<CourseTeacher> Teachers { get; set; }
    [ForeignKey("CourseID")]
    public virtual ICollection<CourseInfo> CourseInfo { get; set; }
    [ForeignKey("CourseID")]
    public virtual ICollection<CourseSession> Sessions { get; set; }
}

    // Controller Delete Action
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Course course = db.Courses.Find(id);

  bool CannotDel = ValidateRelationalData(typeof(course), course);

        //if failed, warn the user and stop the delete action otherwise delete the excited record
    }

    // Public function I was trying to make 
    public static bool ValidateRelationalData(Type anyType, dynamic anyInstance)
    {
            bool IsExisted = anyType.GetProperties().Where(p => (typeof(IEnumerable).IsAssignableFrom(p.PropertyType) && p.PropertyType != typeof(byte[]) && p.PropertyType != typeof(string)))
                                                            .Select(prop => (ICollection)prop.GetValue(anyInstance, null))
                                                            .Where(c => c.Count > 0)
                                                            .Any();

            return IsExisted;
    }





Aucun commentaire:

Enregistrer un commentaire