"T4 must be" dbhelper.ttinclude "T4 connection database get table must"

Source: Internet
Author: User

<#+
Connection Database Configuration
public class Config
{
public static readonly string [email protected] "server=.; Pwd=123;uid=sa;database=oademo; ";
public static readonly string dbdatabase= "Oademo";
}

public class DBHelper
{

#region Getdbtables
Get all tables for the database
public static list<dbtable> Getdbtables (string connectionString, string database, string tables = null)
{

if (!string. IsNullOrEmpty (Tables))
{
Tables = string. Format ("and obj.name in (' {0} ')", tables. Replace (",", "', '"));
}
#region SQL
String sql = string. Format (@ "Select
Obj.name TableName,
Schem.name Schemname,
Idx.rows,
CAST
(
Case
When (SELECT COUNT (1) from sys.indexes WHERE object_id= obj. OBJECT_ID and Is_primary_key=1) >=1 then 1
ELSE 0
END
As BIT) HasPrimaryKey
from {0}.sys.objects obj
Inner JOIN {0}.dbo.sysindexes idx on obj.object_id=idx.id and idx.indid<=1
INNER JOIN {0}.sys.schemas Schem on obj.schema_id=schem.schema_id
where type= ' U ' {1}
ORDER by Obj.name ", database, tables);
#endregion
DataTable dt = getdatatable (connectionString, SQL);
Return dt. Rows.cast<datarow> (). Select (row = new dbtable
{
TableName = row. Field<string> ("tablename"),
SchemaName = row. Field<string> ("Schemname"),
Rows = row. Field<int> ("Rows"),
HasPrimaryKey = row. Field<bool> ("HasPrimaryKey")
}). ToList ();
}
#endregion

#region Getdbcolumns
Get the columns of a table
public static list<dbcolumn> Getdbcolumns (string connectionString, String database, String TableName, String schema = "dbo")
{
#region SQL
String sql = string. Format (@ "
With Indexcte as
(
SELECT
IC.COLUMN_ID,
IC.INDEX_COLUMN_ID,
ic.object_id
from {0}.sys.indexes idx
INNER JOIN {0}.sys.index_columns ic on idx.index_id = ic.index_id and idx.object_id = ic.object_id
WHERE idx.object_id =object_id (@tableName) and Idx.is_primary_key=1
)
Select
colm.column_id ColumnID,
CAST (case when indexcte.column_id was NULL then 0 ELSE 1 END as BIT) IsPrimaryKey,
Colm.name ColumnName,
Systype.name ColumnType,
Colm.is_identity Isidentity,
Colm.is_nullable isnullable,
CAST (colm.max_length as int) ByteLength,
(
Case
When systype.name= ' nvarchar ' and colm.max_length>0 then COLM.MAX_LENGTH/2
When systype.name= ' nchar ' and colm.max_length>0 then COLM.MAX_LENGTH/2
When Systype.name= ' ntext ' and colm.max_length>0 then COLM.MAX_LENGTH/2
else colm.max_length
End
) Charlength,
CAST (colm.precision as int) precision,
CAST (colm.scale as int) scale,
Prop.value Remark
from {0}.sys.columns Colm
Inner JOIN {0}.sys.types systype on colm.system_type_id=systype.system_type_id and Colm.user_type_id=systype.user_ type_id
Left JOIN {0}.sys.extended_properties prop on colm.object_id=prop.major_id and colm.column_id=prop.minor_id
Left JOIN indexcte on colm.column_id=indexcte.column_id and colm.object_id=indexcte.object_id
where colm.object_id=object_id (@tableName)
ORDER by colm.column_id ", database);
#endregion
SqlParameter param = new SqlParameter ("@tableName", SqlDbType.NVarChar, +) {Value = string. Format ("{0}.{ 1}. {2} ", database, Schema, tableName)};
DataTable dt = getdatatable (connectionString, SQL, param);
Return dt. Rows.cast<datarow> (). Select (row = new DbColumn ()
{
ColumnID = row. Field<int> ("ColumnID"),
IsPrimaryKey = row. Field<bool> ("IsPrimaryKey"),
ColumnName = row. Field<string> ("ColumnName"),
ColumnType = row. Field<string> ("ColumnType"),
isidentity = row. Field<bool> ("Isidentity"),
isnullable = row. Field<bool> ("IsNullable"),
ByteLength = row. Field<int> ("ByteLength"),
Charlength = row. Field<int> ("Charlength"),
Scale = row. Field<int> ("scale"),
Remark = row["Remark"]. ToString ()
}). ToList ();
}

#endregion

#regionGetFiles
//Gets all columns of the non-primary key
public static string Getfilestr (String tableName) {
StringBuilder fields = new StringBuilder ();
foreach (DbColumn column in Dbhelper.getdbcolumns (config. ConnectionString, CONFIG. Dbdatabase, TableName) {

if (!column. isidentity) {
fields. Append (column. ColumnName);
Fields. Append (",");
}

}
fields. Remove (fields. length-1,1);
return fields. ToString ();
}
//Gets the parameter of the @ value type
public static string Getparstr (String tableName) {
StringBuilder fields = new StringBuilder ( );
foreach (DbColumn column in Dbhelper.getdbcolumns (config. ConnectionString, CONFIG. Dbdatabase, TableName) {

if (!column. isidentity) {
fields. Append ("@" +column. ColumnName);
Fields. Append (",");
}

}
fields. Remove (fields. length-1,1);
return fields. ToString ();
}
#endregion


#region getdatatable
Based on a SQL query table
public static DataTable getdatatable (String connectionString, String commandtext, params sqlparameter[] parms)
{
using (SqlConnection connection = new SqlConnection (connectionString))
{
SqlCommand Command = connection. CreateCommand ();
Command.commandtext = CommandText;
Command. Parameters.addrange (parms);
SqlDataAdapter adapter = new SqlDataAdapter (command);

DataTable dt = new DataTable ();
Adapter. Fill (DT);

return DT;
}
}

#endregion

Get primary Key
public static string GetPrimaryKey (String tableName)
{
foreach (DbColumn column in Dbhelper.getdbcolumns (config. ConnectionString, CONFIG. Dbdatabase, TableName)) {

if (column. isidentity) {
Return column. ColumnName;
}

}
Return "";
}

}

#region DBTable
<summary>
Table structure
</summary>
public sealed class DBTable
{
<summary>
Table name
</summary>
public string TableName {get; set;}
<summary>
Schema of the table
</summary>
public string SchemaName {get; set;}
<summary>
Number of records in the table
</summary>
public int Rows {get; set;}

<summary>
Whether it contains a primary key
</summary>
public bool HasPrimaryKey {get; set;}
}
#endregion

#region DbColumn
<summary>
table field Structure
</summary>
public sealed class DbColumn
{
<summary>
Field ID
</summary>
public int ColumnID {get; set;}

<summary>
Whether the primary key
</summary>
public bool IsPrimaryKey {get; set;}

<summary>
Field name
</summary>
public string ColumnName {get; set;}

<summary>
Field type
</summary>
public string ColumnType {get; set;}

<summary>
C # types corresponding to database types
</summary>
public string Csharptype
{
Get
{
Return Sqlserverdbtypemap.mapcsharptype (ColumnType);
}
}

<summary>
///
</summary>
Public Type Commontype
{
Get
{
Return Sqlserverdbtypemap.mapcommontype (ColumnType);
}
}

<summary>
byte length
</summary>
public int ByteLength {get; set;}

<summary>
Character length
</summary>
public int Charlength {get; set;}

<summary>
Decimal digits
</summary>
public int scale {get; set;}

<summary>
Whether to increment columns
</summary>
public bool Isidentity {get; set;}

<summary>
Whether to allow empty
</summary>
public bool IsNullable {get; set;}

<summary>
Describe
</summary>
public string Remark {get; set;}
}
#endregion

#region Sqlserverdbtypemap

public class Sqlserverdbtypemap
{
public static string Mapcsharptype (String dbtype)
{
if (string. IsNullOrEmpty (DBTYPE)) return dbtype;
DbType = DbType. ToLower ();
String csharptype = "Object";
Switch (DBTYPE)
{
Case "bigint": Csharptype = "Long"; Break
Case "binary": Csharptype = "byte[]"; Break
Case "bit": Csharptype = "bool"; Break
Case "char": Csharptype = "string"; Break
Case "Date": Csharptype = "DateTime"; Break
Case "datetime": Csharptype = "datetime"; Break
Case "DateTime2": Csharptype = "DateTime"; Break
Case "DateTimeOffset": Csharptype = "DateTimeOffset"; Break
Case "decimal": Csharptype = "decimal"; Break
Case "float": Csharptype = "Double"; Break
Case "image": Csharptype = "byte[]"; Break
Case "int": Csharptype = "int"; Break
Case "Money": Csharptype = "decimal"; Break
Case "nchar": Csharptype = "string"; Break
Case "ntext": Csharptype = "string"; Break
Case "Numeric": Csharptype = "decimal"; Break
case "nvarchar": Csharptype = "string"; Break
Case "real": Csharptype = "single"; Break
Case "smalldatetime": Csharptype = "DateTime"; Break
Case "smallint": Csharptype = "short"; Break
Case "SmallMoney": Csharptype = "decimal"; Break
Case "sql_variant": Csharptype = "Object"; Break
case "sysname": Csharptype = "Object"; Break
Case "text": Csharptype = "string"; Break
Case "Time": Csharptype = "TimeSpan"; Break
Case "Timestamp": Csharptype = "byte[]"; Break
Case "tinyint": Csharptype = "byte"; Break
Case "uniqueidentifier": Csharptype = "Guid"; Break
Case "varbinary": Csharptype = "byte[]"; Break
Case "varchar": Csharptype = "string"; Break
Case "xml": Csharptype = "string"; Break
Default:csharptype = "Object"; Break
}
return csharptype;
}

public static Type Mapcommontype (String dbtype)
{
if (string. IsNullOrEmpty (DBTYPE)) return Type.Missing.GetType ();
DbType = DbType. ToLower ();
Type Commontype = typeof (object);
Switch (DBTYPE)
{
Case "bigint": Commontype = typeof (Long); Break
Case "binary": Commontype = typeof (byte[]); Break
Case "bit": Commontype = typeof (bool); Break
Case "char": Commontype = typeof (String); Break
Case "Date": Commontype = typeof (DateTime); Break
Case "datetime": Commontype = typeof (DateTime); Break
Case "DateTime2": Commontype = typeof (DateTime); Break
Case "DateTimeOffset": Commontype = typeof (DateTimeOffset); Break
Case "decimal": Commontype = typeof (decimal); Break
Case "float": Commontype = typeof (Double); Break
Case "image": Commontype = typeof (byte[]); Break
Case "int": Commontype = typeof (int); Break
Case "Money": Commontype = typeof (decimal); Break
Case "nchar": Commontype = typeof (String); Break
Case "ntext": Commontype = typeof (String); Break
Case "Numeric": Commontype = typeof (decimal); Break
case "nvarchar": Commontype = typeof (String); Break
Case ' real ': Commontype = typeof (Single); Break
Case "smalldatetime": Commontype = typeof (DateTime); Break
Case "smallint": Commontype = typeof (short); Break
Case "SmallMoney": Commontype = typeof (decimal); Break
Case "sql_variant": Commontype = typeof (object); Break
case "sysname": Commontype = typeof (object); Break
Case "text": Commontype = typeof (String); Break
Case "Time": Commontype = typeof (TimeSpan); Break
Case "Timestamp": Commontype = typeof (byte[]); Break
Case "tinyint": Commontype = typeof (Byte); Break
Case "uniqueidentifier": Commontype = typeof (Guid); Break
Case "varbinary": Commontype = typeof (byte[]); Break
Case "varchar": Commontype = typeof (String); Break
Case "xml": Commontype = typeof (String); Break
Default:commontype = typeof (object); Break
}
return commontype;
}
}
#endregion

#>

"T4 must be" dbhelper.ttinclude "T4 connection database get table must"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.