vendredi 3 mars 2017

Entity Framework adding to N to N by reflection

I want to create a function that dynamically adds Entity to other Entity collection. For example I have many entities like this

public class User : IEntity
{
    public User()
    {    
        Rules = new HashSet<Ecreportrule>();
    }        
    public ICollection<Rule> Rules{ get; set; }
}   
public class User : IEntity
{
    public User()
    {        
        Users = new HashSet<User>();            
    }        
    public ICollection<User> Users { get; set; }
}

Which have many to many relationship. I need to create function that adds the entity to others many to many relation trough the reflection. Function should look like this:

public static void AddNtoN(string EntitySourceName, string PropertyNtoN, IEntity object)

I can retrieve the source entity:

 var entityProperty = db.GetType().GetProperties().Where(t => t.Name == EntitySourceName+"s").Single();
 var baseQuery = (IQueryable<IEntity>)entityProperty.GetValue(db, null);
 var Item= baseQuery.Where(p => p.Id == ID).FirstOrDefault();

But was not successful to add object into items N:N collection. so basically I need to access the PropertyNtoN by its name and add object to the collection. Thanks





Aucun commentaire:

Enregistrer un commentaire