C # automatically create database tables based on the object class by using custom features,

Source: Internet
Author: User

C # automatically create database tables based on the object class by using custom features,

New users of. Net usually tend to confuse attributes with attributes. In fact, they are two different things.

Attribute refers to the data fields encapsulated in the class, and the attribute is declarative information for the class, field, method, and attribute element annotation.

The following code (the property of Id and Name is User, and the property of [DbKey] is Id)

/// <Summary> /// User information /// </summary> public class User {[DbKey] public string Id {get; set;} public string Name {get; set ;}}

Features are divided into predefined features and custom features. This section describes custom features.

What problems can features solve?

What if we need to dynamically create the corresponding database table by defining some entity classes?

Directly Add code

Namespace CustomerAttribute {// <summary> // database primary key // </summary> public class DbKey: Attribute {public string Description {get; set;} public DbKey () {} public DbKey (string description) {this. description = description ;}}}
Namespace CustomerAttribute {// <summary> // User information // </summary> public class User {[DbKey] public string Id {get; set ;} public string Name {get; set ;}/// <summary> /// User Role /// </summary> public class UserRole {[DbKey ("User ID")] public string UserId {get; set;} [DbKey ("role ID")] public string RoleId {get; set ;}}}
Namespace CustomerAttribute {class Program {// <summary> // obtain the primary key field of the database /// </summary> /// <typeparam name = "T"> </typeparam >/// <returns> </returns> private static IEnumerable <PropertyInfo> getDbKeyFields <T> () {// obtain the public field var fields = typeof (T) in the current class ). getProperties (); // search for the field var keyFields = fields with the DbKey feature. where (field => (DbKey) Attribute. getCustomAttribute (field, typeof (DbKey ))! = Null); return keyFields;} private static string getDescription (PropertyInfo field) {string result = string. empty; var dbKey = (DbKey) Attribute. getCustomAttribute (field, typeof (DbKey); if (dbKey! = Null) result = dbKey. description; return result;} static void Main (string [] args) {try {var userKeyFields = getDbKeyFields <User> (); Console. writeLine ("the primary key of the User table is:" + string. join (",", userKeyFields. select (field => field. name); var userRoleKeyFields = getDbKeyFields <UserRole> (); Console. writeLine ("primary key of the UserRole table:" + string. join (",", userRoleKeyFields. select (field => field. name); foreach (PropertyInfo field in userRoleKeyFields) {string description = getDescription (field); Console. writeLine (string. format ("{0} field Description: {1}", field. name, description) ;}} catch (Exception ex) {Console. writeLine (ex);} finally {Console. readLine ();}}}}
View Code

From the code above, we can see that the feature itself is also a class that inherits from the Attribute class. We can mark the features of the class, method, Attribute, and other elements.

The above is a simple example. We can use the custom [DbKey] feature to mark the field on which the primary key needs to be set.

When you need to dynamically create a database, you can parse the table name, field name, primary key field, field description, and so on from the entity class, then generate a script to create a database table, and dynamically create a database table.

Code for creating a database. You can add it later.

The code first mode of entity framework is used to read the required information for creating a database table from the feature.

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.