mardi 26 mai 2015

How to build generic Lamda Expressions in C# for any Entity and any Proprerty and Navigation

I'd like somebody to help me building lamda expressions so as to become generic by reflection. I have the following function which returns the entity type by its name:

private Type GetEntityType(string EntityName)
{
    Assembly Data = Assembly.Load("Domain.Entities");
            Type type = Data.GetTypes()
            .Where(t => t.IsClass && t.Namespace == "Domain.Entities" && t.Name == EntityName)
            .ToList<Type>().First();
    return type;
}   

So if I have some related entities for example Customers, Purchases and Items:

public partial class Customers
{

    public Customers()
    {
        this.Purchases = new HashSet<Purchases>();
    }

    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

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

public partial class Purchases
{

    public Purchases()
    {
    }

    [Key]
    public int Id { get; set; }
    public Date DatePurchased { get; set; }

    public virtual Customers Customers { get; set; }
    public virtual Items Items { get; set; }
}

public partial class Items
{

    public Items()
    {
        this.Purchases = new HashSet<Purchases>();
    }

    [Key]
    public int Id { get; set; }
    public string NameOfItem { get; set; }

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

I can have expressions for Customers like:

c => c.Name
c => c.Name == "My name"
c => c.Name.Contains("My name")

For Purchases I could have:

p => p.Customers
p => p.Customers.Name
p => p.Customers.Name == "My Name"
p => p.Customers.Name.Contains("My Name")

I could also navigate from Customers to Items properties... but that would be a further step to me since I'd first need to transform those Expressions to generic so as to build them by any given Entity for which we know its name (returned by the function GtEntityType above) and any given property names and navigations like those in example.

Appreciated your help so much.





Aucun commentaire:

Enregistrer un commentaire