从DbContext获取表名和列名

时间:2014-03-27 20:43:27

标签: entity-framework entity-framework-6.1

使用新的Public Mapping API,从实体到获取相应的数据库模式和表名,以及将实体属性映射到列名称的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

以下是使用Database First方法生成的ADO.NET实体数据模型的参考。它使用DbContext连接提供的模式。

未强制执行架构限制,但只返回更清晰的结果。如需了解更多信息,请查看 https://msdn.microsoft.com/en-us/library/cc716722(v=vs.110).aspx

  using (var dbContext = new DbGeneratedByEfEntities())
  {
    var conn = dbContext.Database.Connection;
    conn.Open();

    var restrictions = default(string[]);

    // please replace DbName and Owner with the actual value
    restrictions = new string[] { "DbName", "dbo" };

    // get DataTable from schema with collection name of "Tables"
    var tablesDataTable = conn.GetSchema(SqlClientMetaDataCollectionNames.Tables, restrictions);

    // show column names
    Debug.WriteLine(string.Join(" | ", tablesDataTable.Columns.Cast<DataColumn>()));

    // show row contents, table names from schema
    tablesDataTable.Rows.Cast<DataRow>().ToList().ForEach(r =>
    {
      Debug.WriteLine(string.Join(" | ", r.ItemArray));
    });

    /************************/

    // please replace DbName, Owner and TableName with the actual value
    restrictions = new string[] { "DbName", "dbo", "TableName" };

    // get DataTable from schema with collection name of "Columns"
    var colsDataTable = conn.GetSchema(SqlClientMetaDataCollectionNames.Columns, restrictions);

    // show column names
    Debug.WriteLine(string.Join(" | ", colsDataTable.Columns.Cast<DataColumn>()));

    // show row contents, field names from schema
    colsDataTable.Rows.Cast<DataRow>().ToList().ForEach(r =>
    {
      Debug.WriteLine(string.Join(" | ", r.ItemArray));
    });
  }