lundi 13 juin 2016

Generate DbContext using CSharpCodeProvider

using the below code i generate OnlineShopContext at runtime

           string code = @"
           using System.Data.Entity;
           using GenerateContext.Models;
           using System.Data.Entity.Core.EntityClient;
           using GenerateContext.Models.Mapping;

           namespace GenerateContext.Models
           {
public partial class OnlineShopContext : DbContext
{
    static OnlineShopContext()
    {
        Database.SetInitializer<OnlineShopContext>(null);
    }

    public OnlineShopContext()
        : base(""Name = OnlineShopContext"")
    {
        }

  public DbSet<Customer> Customers { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<OrderItem> OrderItems { get; set; }
    public DbSet<Product> Products { get; set; }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new CustomerMap());
        modelBuilder.Configurations.Add(new OrderMap());
        modelBuilder.Configurations.Add(new OrderItemMap());
        modelBuilder.Configurations.Add(new ProductMap());
    }

}
}
";

        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerParameters parameters = new CompilerParameters();

        // Reference to System.Drawing library
        parameters.ReferencedAssemblies.Add("System.Drawing.dll");
        parameters.ReferencedAssemblies.Add("System.Data.dll");
        parameters.ReferencedAssemblies.Add("System.Data.Entity.dll");
        parameters.ReferencedAssemblies.Add("System.ComponentModel.dll");
      parameters.ReferencedAssemblies.Add(typeof(Customer).Assembly.Location);
                       parameters.ReferencedAssemblies.Add(typeof(CustomerMap).Assembly.Location);
                       parameters.ReferencedAssemblies.Add(typeof(DbSet).Assembly.Location);
                       parameters.ReferencedAssemblies.Add(typeof(DbContext).Assembly.Location);
                       parameters.ReferencedAssemblies.Add(typeof(IQueryable).Assembly.Location);
                                      parameters.ReferencedAssemblies.Add(typeof(IQueryable<>).Assembly.Location);
                       parameters.ReferencedAssemblies.Add(typeof(System.ComponentModel.IListSource).Assembly.Location);

        parameters.GenerateExecutable = false;
        parameters.GenerateInMemory = false;
        parameters.OutputAssembly = "OutputAssembly.dll";

        CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);

        if (results.Errors.HasErrors)
        {
            StringBuilder sb = new StringBuilder();

            foreach (CompilerError error in results.Errors)
            {
                sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
            }

            throw new InvalidOperationException(sb.ToString());
        }

and the generated assembly is :(using ILSpy)

using GenerateContext.Models.Mapping;
using System;
using System.Data.Entity;

namespace GenerateContext.Models
{
public class OnlineShopContext : DbContext
{
    public DbSet<Customer> Customers
    {
        get;
        set;
    }

    public DbSet<Order> Orders
    {
        get;
        set;
    }

    public DbSet<OrderItem> OrderItems
    {
        get;
        set;
    }

    public DbSet<Product> Products
    {
        get;
        set;
    }

    static OnlineShopContext()
    {
        Database.SetInitializer<OnlineShopContext>(null);
    }

    public OnlineShopContext() : base("Name = OnlineShopContext")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add<Customer>(new CustomerMap());
        modelBuilder.Configurations.Add<Order>(new OrderMap());
        modelBuilder.Configurations.Add<OrderItem>(new OrderItemMap());
        modelBuilder.Configurations.Add<Product>(new ProductMap());
    }
}

}

when I want to create instance and run a query for example FirstOrDeafult or Where, These methods are not there. but there is Find method which doesn't run because of mismatch data type that is strange

        Assembly assembly = results.CompiledAssembly;
        Type type = assembly.GetType("GenerateContext.Models.OnlineShopContext");
        dynamic db = (DbContext)Activator.CreateInstance(type);
        var obj = db.Customers.GetType();
        MethodInfo main = obj.GetMethod("Find");
        object[] parametersArray = new object[] { 100 };
        var customer = main.Invoke(obj, parametersArray);

How can I do it ? How can I cast the instance to a type and work with it strongly type to fetch data with Where or FirstOrDefault





Aucun commentaire:

Enregistrer un commentaire