如何在运行时创建模型? [英] how to create model at run time?

查看:48
本文介绍了如何在运行时创建模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我通过提供表名(例如学生)并向该表添加字段然后保存表来动态创建表。现在,我的表是在SQL Server数据库中创建的。现在假设表有数据,我想在WebGrid上显示表(ex student)的数据。但是,问题是我没有该表的模型(例如学生)。那么,我如何为新创建的表创建模型或如何在WebGrid上显示数据?





谢谢!

In my project i dynamically creating table by giving table name (ex. student) and adding fields to that table and then save table. Now, my table is created in SQL Server database. Now assume table has data and i want to show the data of table (ex student) on WebGrid. But, the problem is i have no model for that table (ex. student). So, How i can create model for newly created table or how i can show the the data on WebGrid?


Thank You !

推荐答案

1-创建模型CurrentReport.cs

1- Create a model CurrentReport.cs
public class CurrentReport
    {   
        //both property contain data from a two different table    
        public IEnumerable<tablesfield> OTablesFields { get; set; } //for webgrid header
        public List<dynamic> dataField { get; set; } //for grid data
    }





2-现在,在控制器中创建Actionmethod,例如





2- Now, create Actionmethod in controller like

public ActionResult Report(int tableId)
        {
            ReportUtility OReportUtility = new ReportUtility();   //ReportUtility class Object
            CurrentReport OCurrentReport = new CurrentReport();   //model object

            OCurrentReport.dataField = OReportUtility.getTableData(tableId);   //grid data

            OCurrentReport.OTablesFields = OReportUtility.getColumns(tableId);  //grid column names

            return PartialView(OCurrentReport);
        }





3-然后创建getTableData()& ReportUtility类中的getColumns()





3- Then create getTableData() & getColumns() in ReportUtility Class

public List<dynamic> getTableData(int tableId)
        {
            try
            {
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter();
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NewConnection"].ConnectionString);
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM " + getTableName(tableId), con);
                da.SelectCommand = cmd;
                da.Fill(dt);

                da.Dispose();
                con.Close();

                var result = new List<dynamic>();
                foreach (DataRow row in dt.Rows)
                {
                    var obj = (IDictionary<string,>)new ExpandoObject();
                    foreach (DataColumn col in dt.Columns)
                    {
                        obj.Add(col.ColumnName, row[col.ColumnName]);
                    }
                    result.Add(obj);
                }               
                return result;
            }
            catch (Exception ex)
            {
                return null;
            }            
        }







public string getTableName(int tableId)
       {
           var context = new DBEntities();

           var tname = (from t in context.Table
                        where t.Id == tableId
                        select t.tableName).First();

           return tname.ToString();
       }







public IEnumerable<tablesfield> getColumns(int tableId)
       {
           var context = new DBEntities();
           var columns = from tf in context.TablesField
                         where tf.tableId == tableId
                         select tf;

           return columns;
       }







4-现在查看








4- Now on View


@model WDCS.MODELS.CurrentReport

<div id="PartialPage">

@{
    var grid = new WebGrid( Model.dataField , rowsPerPage: 5, canPage: true, canSort: true, ajaxUpdateContainerId: "Grid");

        List<webgridcolumn> cols = new List<webgridcolumn>();
   
        foreach (var clm in Model.OTablesFields)
        {
            cols.Add(grid.Column(clm.fieldName, clm.displayName));        
        }        
                                                                                              
    }


    <div id="Grid">
          @grid.GetHtml(
                        tableStyle:"webGrid",
                        headerStyle:"header",
                        alternatingRowStyle:"alt",
                        columns:cols           
                       )
       
    </div>

</div>





而已。只提供表id并在webgrid上显示任何表数据。



That's it. just provide table id and it display any table data on webgrid.




看看这个例子。你可以用一个字符串来创建你的model.it string可以将你创建的表字段放入database.I希望它可以帮助你:



Hi,
look at this example.You can use a string for create your model.it string can have your table fields that you create into database.I hope it can help you:

     string modelDefinition = @"using System;
     using System.CodeDom.Compiler;
     using System.Collections.Generic;
     using System.ComponentModel.DataAnnotations;
     using System.Web;
     using Microsoft.CSharp;

 namespace PhoneBookApplication.Models
  {
    public class Phonebook
    {
        public Phonebook(int id, string name, string Fname, string mail, String mobile, int age,     string address)
        {
            ID = id;
            Name = name;
            Email = mail;
            Mobile = mobile;
            Age = age;
            Address = address;
        }
        public Phonebook() { }
        [Key]
        public int ID { get; set; }

       
        public string Name { get; set; }


        public string Email { get; set; }

      
        public string Mobile { get; set; }

   
        public int Age { get; set; }

       
        public String Address { get; set; }
    }
}";

  var providerOptions = new Dictionary<string,>();

            providerOptions.Add("CompilerVersion", "v4.0");

            CSharpCodeProvider codeProvider = new CSharpCodeProvider(providerOptions);

            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(new string[] { "System.dll", "System.ComponentModel.DataAnnotations.dll" });

            parameters.GenerateInMemory = true;
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, modelDefinition);
            if (results.Errors.Count > 0)
            {
                string err = string.Empty;
                foreach (CompilerError CompErr in results.Errors)
                {
                    err = err +
                                "Line number " + CompErr.Line +
                                ", Error Number: " + CompErr.ErrorNumber +
                                ", '" + CompErr.ErrorText + ";" +
                                Environment.NewLine + Environment.NewLine;
                }
                throw new Exception(err);
            }
            Type t = results.CompiledAssembly.GetType("PhoneBookApplication.Models.Phonebook");

            object model = Activator.CreateInstance(t);

            System.Reflection.PropertyInfo[] ModelProperties = model.GetType().GetProperties();


这篇关于如何在运行时创建模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆