csharp LINQPad脚本,用于获取有关当前所选数据库的基本架构信息(假设LINQPad的默认数据上下文创建方法)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp LINQPad脚本,用于获取有关当前所选数据库的基本架构信息(假设LINQPad的默认数据上下文创建方法)相关的知识,希望对你有一定的参考价值。

void Main()
{
    var databaseInfo = GetDatabaseInfo(this);
    databaseInfo.Dump();
}

// Define other methods and classes here
public class DatabaseInfo
{
    public Type DataContextType { get; set; }
    public string DatabaseName { get; set; }
    public string DatabaseServer { get; set; }
    public TableInfo[] Tables { get; set; }
}

public class TableInfo
{
    public Type TableType { get; set; }
    public Type EntityType { get; set; }
    public string TableName { get; set; }
    public ColumnInfo[] Columns { get; set; }
}

public class ColumnInfo
{
    public string ColumnName { get; set; }
    public string DatabaseType { get; set; }
}

public DatabaseInfo GetDatabaseInfo(LINQPad.DataContextBase dataContext)
{
    return new DatabaseInfo
    {
        DatabaseName = dataContext.Connection.Database,
        DatabaseServer = dataContext.Connection.DataSource,
        DataContextType = dataContext.GetType(),
        Tables = GetTables(dataContext.GetType()),
    };
}

public TableInfo[] GetTables(Type dataContextType)
{
    var tableInfoQuery =
        from prop in dataContextType.GetProperties()
        where prop.PropertyType.IsGenericType
        where prop.PropertyType.GetGenericTypeDefinition() == typeof(Table<>)
        let tableType = prop.PropertyType
        let entityType = tableType.GenericTypeArguments.Single()
        select new TableInfo
        {
            TableName = GetTableNameFromEntityType(entityType),
            EntityType = entityType,
            TableType = tableType,
            Columns = GetColumnsFromEntityType(entityType),
        };
    
    return tableInfoQuery.ToArray();
}

public string GetTableNameFromEntityType(Type entityType)
{
    var tableNameQuery =
        from ca in entityType.CustomAttributes
        from na in ca.NamedArguments
        where na.MemberName == "Name"
        select na.TypedValue.Value.ToString();
        
    return tableNameQuery.Single();
}

public ColumnInfo[] GetColumnsFromEntityType(Type entityType)
{
    var columnInfoQuery =
        from field in entityType.GetFields()
        from attribute in field.CustomAttributes
        from namedArgument in attribute.NamedArguments
        where namedArgument.MemberName == "DbType"
        select new ColumnInfo
        {
            ColumnName = field.Name,
            DatabaseType = namedArgument.TypedValue.Value.ToString(),
        };
       
    return columnInfoQuery.ToArray();
}

以上是关于csharp LINQPad脚本,用于获取有关当前所选数据库的基本架构信息(假设LINQPad的默认数据上下文创建方法)的主要内容,如果未能解决你的问题,请参考以下文章

csharp 简单的LinqPad示例命中端点

csharp 简单的LinqPad示例命中端点

csharp LinqPadでNUnit的する

csharp 这是KeyPressed e.Handled的LinqPad示例

csharp 这是KeyPressed e.Handled的LinqPad示例

csharp LINQPad片段声明了两个字符串数组,吐出了它们互斥的部分。