简体   繁体   English

使用反射查找集合属性,然后添加到集合

[英]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. 然后,我有以下代码,试图在MainTable和LookupTable之间添加关系。 I am first passing the two table class types and passing the record to add and the name of the collection property. 我首先传递两种表类类型,并传递要添加的记录和collection属性的名称。

The problem is the "collectionField" is NULL whenever I try to cast it (ICollection(MainTable)). 问题是每当我尝试将其转换为(ICollection(MainTable))时,“ collectionField”为NULL。 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. 我需要“ collectionField”成为ICollection(MainTable)类型,以便可以添加MainTable记录,除非我以错误的方式进行操作。

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);           
    }

From the comments I've decided to change my approach to this. 根据评论,我决定更改此方法。 If anyone is interested the below code works. 如果有人感兴趣,下面的代码将起作用。

public void AddRelationalRecord(object recordToAdd, object recordWithCollection, string collectionFieldName)
{
    var collectionProp = recordWithCollection.GetType().GetProperty(fieldName);
    collectionProp.PropertyType.GetMethod("Add").Invoke(aaa.GetValue(recordWithCollection, null), new object[] { recordToAdd });           
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM