In ASP. NET, Entity classes are generated based on anonymous classes, datatable, and SQL statements.

Source: Internet
Author: User

In ASP. NET, Entity classes are generated based on anonymous classes, datatable, and SQL statements.

This article mainly introduces how to generate entity classes based on anonymous classes, datatable, and SQL in ASP. NET. This small tool class is very practical and easy to use. For more information, see

These situations may occur during development:

1. The anonymous objects queried by EF or LINQ are not convenient to call in other places, and they are also lazy to manually create object classes.

2. You need to create a class to reflect objects through datatable.

3. You also need to create a class for the entities returned by SQL statements.

4. If you want to write a template through the Code Generator, you need to install or do not want to generate a bunch of unused classes.

To solve the above inconvenience, I encapsulated an entity generation class, which can be thrown into the program for arbitrary calls.

Encapsulation class:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. Data;

Using System. Data. SqlClient;

Using System. Text. RegularExpressions;

 

Namespace SyntacticSugar

{

/// <Summary>

/// ** Description: entity generation class

/// ** Founding Date:

/// ** Modification time :-

/// ** Prepared by sunkaixuan

/// ** Qq: 610262374 welcome to the exchange, joint improvement, naming syntax, and other poorly written areas. You are welcome to give valuable suggestions.

/// </Summary>

Public class ClassGenerating

{

/// <Summary>

/// Obtain the object class String Based on the anonymous class

/// </Summary>

/// <Param name = "entity"> anonymous object </param>

/// <Param name = "className"> generated class name </param>

/// <Returns> </returns>

Public static string DynamicToClass (object entity, string className)

{

StringBuilder reval = new StringBuilder ();

StringBuilder propertiesValue = new StringBuilder ();

Var propertiesObj = entity. GetType (). GetProperties ();

String replaceGuid = Guid. NewGuid (). ToString ();

String nullable = string. Empty;

Foreach (var r in propertiesObj)

{

 

Var type = r. PropertyType;

If (type. IsGenericType & type. GetGenericTypeDefinition () = typeof (Nullable <> ))

{

Type = type. GetGenericArguments () [0];

Nullable = "? ";

}

If (! Type. Namespace. Contains ("System. Collections. Generic "))

{

PropertiesValue. AppendLine ();

String typeName = ChangeType (type );

PropertiesValue. AppendFormat ("public {0} {3} {1} {2}", typeName, r. Name, "{get; set ;}", nullable );

PropertiesValue. AppendLine ();

}

}

 

Reval. AppendFormat (@"

Public class {0 }{{

{1}

}}

", ClassName, propertiesValue );

 

 

Return reval. ToString ();

}

 

 

/// <Summary>

/// Obtain the object class String Based on the DataTable

/// </Summary>

/// <Param name = "SQL"> </param>

/// <Param name = "className"> </param>

/// <Returns> </returns>

Public static string DataTableToClass (DataTable dt, string className)

{

StringBuilder reval = new StringBuilder ();

StringBuilder propertiesValue = new StringBuilder ();

String replaceGuid = Guid. NewGuid (). ToString ();

Foreach (DataColumn r in dt. Columns)

{

PropertiesValue. AppendLine ();

String typeName = ChangeType (r. DataType );

PropertiesValue. AppendFormat ("public {0} {1} {2}", typeName, r. ColumnName, "{get; set ;}");

PropertiesValue. AppendLine ();

}

Reval. AppendFormat (@"

Public class {0 }{{

{1}

}}

", ClassName, propertiesValue );

 

 

Return reval. ToString ();

}

 

/// <Summary>

/// Obtain the object class String Based on the SQL statement

/// </Summary>

/// <Param name = "SQL"> SQL statement </param>

/// <Param name = "className"> generated class name </param>

/// <Param name = "server"> service name </param>

/// <Param name = "database"> database name </param>

/// <Param name = "uid"> account </param>

/// <Param name = "pwd"> password </param>

/// <Returns> </returns>

Public static string SqlToClass (string SQL, string className, string server, string database, string uid, string pwd)

{

Using (SqlConnection conn = new SqlConnection (string. format ("server = {0}; uid = {2}; pwd = {3}; database = {1}", server, database, uid, pwd )))

{

SqlCommand command = new SqlCommand ();

Command. Connection = conn;

Command. CommandText = SQL;

DataTable dt = new DataTable ();

SqlDataAdapter sad = new SqlDataAdapter (command );

Sad. Fill (dt );

Var reval = DataTableToClass (dt, className );

Return reval;

}

}

/// <Summary>

/// Obtain the object class String Based on the SQL statement

/// </Summary>

/// <Param name = "SQL"> SQL statement </param>

/// <Param name = "className"> generated class name </param>

/// <Param name = "connName"> connectionStrings name of webconfig </param>

/// <Returns> </returns>

Public static string SqlToClass (string SQL, string className, string connName)

{

String connstr = System. Configuration. ConfigurationManager. ConnectionStrings [connName]. ToString ();

If (connstr. Contains ("metadata") // ef

Connstr = Regex. Match (connstr, @ "connection string \ =" "(. +)" "). Groups [1]. Value;

Using (SqlConnection conn = new SqlConnection (connstr ))

{

SqlCommand command = new SqlCommand ();

Command. Connection = conn;

Command. CommandText = SQL;

DataTable dt = new DataTable ();

SqlDataAdapter sad = new SqlDataAdapter (command );

Sad. Fill (dt );

Var reval = DataTableToClass (dt, className );

Return reval;

}

}

/// <Summary>

/// Matching type

/// </Summary>

/// <Param name = "type"> </param>

/// <Returns> </returns>

Private static string ChangeType (Type type)

{

String typeName = type. Name;

Switch (typeName)

{

Case "Int32": typeName = "int"; break;

Case "String": typeName = "string"; break;

}

Return typeName;

}

}

}

The call is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

// Generate object classes using anonymous objects

Var dynamicObj = new {id = 1, name = "", entity = new enityt1 ()};

// Note: only a single object cannot be passed into the List <T>, and the set must be List [0]

String classCode = ClassGenerating. DynamicToClass (dynamicObj, "classDynamic ");

 

 

// Generate object classes through datatable

DataTable dt = new DataTable ();

Dt. Columns. Add ("Id", typeof (int ));

Dt. Columns. Add ("Name ");

 

ClassCode = ClassGenerating. DataTableToClass (dt, "classTatabale ");

 

 

// Use SQL statements to generate entity classes

ClassCode = ClassGenerating. SqlToClass ("select * from note", "Note", "127.0.0.1", "MyWork", "sa", "sasa ");

ClassCode = ClassGenerating. SqlToClass ("select * from dbo. AccessoriesDetail", "AccessoriesDetail", "NFDEntities"); // use the config connstring name

Then, in the debugging status, CTRL + C the desired result and create a new class CTRL + V.

Related Article

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.