vendredi 5 mai 2017

Find a collection property using reflection then add to collection

I am trying to create a generic function to add relational records in entity framework. I am working on the following solution. Though if I am going about this all wrong could you direct me in the right direction.

I have the following to classes. Also to note this is a code first approach in entity framework.

public class MainTable
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int MainTableID { get; set; }

    public int LookupID { get; set; }

    [ForeignKey("LookupID")]
    public virtual LookupTable Lookups { get; set; }
}

public class LookupTable
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int LookupID{ get; set; }

    public string LookupText { get; set; }

    public virtual ICollection<MainTable> MainTable { get; set; }
}

I then have the following code that I am trying to add an relationship between MainTable and LookupTable. I am first passing the two table class types and passing the record to add and the name of the collection property.

The problem is the "collectionField" is NULL whenever I try to cast it (ICollection(MainTable)). I need to "collectionField" to become of type ICollection(MainTable) so I can add the MainTable record, unless I am going about this the wrong way.

public void AddRelationalRecord<MainTableType, LookupTableType>(MainTableType recordToAdd, string collectionFieldName)  
where MainTableType: class                                                                                                             
where LookupTableType: class
    {
        var collectionField = typeof(LookupTableType)
                                        .GetProperties()
                                        .Where(prop => prop.Name == collectionFieldName)
                                        .FirstOrDefault();

        collectionField.Add(recordToAdd);           
    }





Aucun commentaire:

Enregistrer un commentaire