2

使用新的公共映射 API,从实体到获取相应的数据库架构和表名以及实体属性到列名的映射的正确方法是什么?

4

1 回答 1

0

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

Schema Restriction 不是强制执行的,只是返回更清晰的结果。有关详细信息,请查看 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));
    });
  }
于 2015-05-19T10:18:26.190 回答