Simple Application of Entityframework, entityframework
Use EntityFramework in the project
Project code: http://yunpan.cn/cKAw3sSJWQwUX extract code 871c
Poor writing and poor technology. To improve yourself, we welcome criticism. Finally, let me know if you have any questions. Thank you. (Mailbox: jin_wangjia@163.com)
Preface 1
1. Establish solution project structure 1
2. Import EntityFramework Class Library 1
3. Compile Object Class 1
4. Edit connection string 3
5. Write BaseBLL Class 3
6. Write Business Processing Class 4
7. Write Business Processing Class 6
8. application 6
9. intractable diseases 7
Preface
The use of databases accounts for a large proportion in software programming. Especially in the management system, basically no system can leave the database and exist independently. When writing database access programs, the most troublesome thing is to fight SQL. Generally, You need to reverse the SQL statements in the database and VS many times to write the statement we want. The emergence of ORM solves this problem well. It can convert the compilation of SQL-related programs into statements of similar strong types, which facilitates the compilation and debugging and greatly improves the work efficiency. The following describes how to use EntiryFramework in a project to make a simple record. Development Environment: VS2010, SQLServer208, EntityFramework6
1. Establish a solution project structure
EntityFramework is used to access the database. The type of the root project does not matter. We can use it in a C/S project or B/S project. To demonstrate how to use EntityFramework, we must first establish an example solution. The most basic layer-3 structure of this solution, because data access is mainly implemented by EntityFramework, the implementation of the data access layer is basically invisible, this makes the entire solution look like a two-tier solution. The following table describes the types and usage of each project in this solution.
Project name |
Level |
Type |
Function |
Whether to introduce EF |
JZAPP |
Presentation Layer |
Applications |
Applications |
No |
BLL |
Business logic layer |
Class Library |
Logical operations and data access |
Yes |
Model |
Entity class |
Class Library |
Database Table-to-class ing |
Yes |
2. Import the EntityFramework class library
Use Nuget to import the latest EntityFramework to BLL and Model projects.
3. Compile entity classes
In the following figure, this entity class is used as a sample to learn how to define the entity class in EntityFramework. The entity class is the ing of database tables, so the names, attribute names, and attribute types of this class are all associated with the tables we designed. The Type ing in a specific database is C #, and no detailed research has been done. The following is a summary. If other types are used in the future, they will be added here.
Type in SqlServer |
Type in C # |
Varchar (N) |
String |
Bit |
Bool |
Datetime |
DateTime |
Int |
Integer |
The database is defined as follows:
Based on the table, we can write the above database tables as the following entity classes, and put the entity classes in the Model project:
Using System. componentModel. dataAnnotations. schema; using System. componentModel. dataAnnotations; namespace Model {[Table ("User")] public class UserDefinition {// <summary> // used? User § id // </summary> [Key, DatabaseGenerated (DatabaseGeneratedOption. none)] public string UserId {set; get;} public string LoginName {set; get;} public string Name {set; get;} public string Password {set; get ;} public bool Sex {set; get;} public string DeptId {set; get;} public DateTime CreateDate {set; get;} public int Status {set; get ;} public string SizeId {get; set;} public bool Visible {get; set ;}}}View Code
- [Table ("User")]: defines the database Table corresponding to UserDefinition as User
- [Key]: defines UserId as the primary Key.
- [DatabaseGenerated (DatabaseGeneratedOption. None)]: defines the data generation items of the field. DatabaseGeneratedOption has three values: Identity: auto-growth; None: not processed; Computed: calculation column.
4. Edit the connection string
The connection string is stored in the configuration file (app. config) of the JZAPP project. If this file exists in the project, use it directly. If no file exists, create a new one.
Add a connectionStrings section in the configuration file. It is a child node of configuration.
<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <connectionStrings> <add name = "ABC" connectionString = "Data Source = 127.0.0.1; Initial Catalog = abc; Persist Security Info = True; User ID = sa; password = landmark "providerName =" System. data. sqlClient "/> </connectionStrings> </configuration>View Code
- Name: Name of the connection string. It is used in the BaseBLL constructor in this program.
- Data Source: database server name, which can also be IP address or URL
- Initial Catalog: Database Name loan
- User ID: User Name of the database
- Password: Database Password
5. Compile the BaseBLL class
This class is the basis for accessing the database. With this class, you can write other services for processing. If there is no business processing, you can use this class to operate the database directly. It must inherit from DbContext.
Using System. data. entity; using Model; using System. data. entity. sqlServer; namespace BLL {public class BaseBLL: DbContext {public DbSet <UserDefinition> User {get; set;} public BaseBLL (): base ("abc "){}}}View Code
Note the following three points for writing this class:
- BaseBLL must inherit from DbContext
- Instantiate each object class with DbSet <> type
- Assign the name of the connection string to the constructor.
6. Write Business Processing superclass
We can write code for different businesses. In program development, when there is too much repetition, we can summarize it and write the following common functions, define them as a parent class:
Public class ParentBLL <T> where T: class {public virtual void Add (T p) {using (BaseBLL bll = new BaseBLL () {bll. set <T> (). add (p); bll. saveChanges () ;}} public T Find (object p) {using (BaseBLL bll = new BaseBLL () {return bll. set <T> (). find (p) ;}} public IList <T> Query () {using (BaseBLL bll = new BaseBLL () {return (from o in bll. set <T> () select o ). toList () ;}} public virtual void Remove (T p) {using (BaseBLL bll = new BaseBLL () {bll. set <T> (). attach (p); bll. set <T> (). remove (p); bll. saveChanges () ;}} public virtual void Update (T p) {using (BaseBLL bll = new BaseBLL () {bll. entry (p ). state = EntityState. modified; bll. saveChanges ();}}}View Code
7. Compile the business processing class
The business processing class should be very simple at the beginning. We started to use the parent class of the business processing class to implement it.
Using Model; using System. Data. Entity. SqlServer; namespace BLL {public class UserBLL: ParentBLL <UserDefinition> {}}View Code8. create a database SQLcreate table "User" (UserId varchar (100) not null, LoginName varchar (100) null, Name varchar (100) null, Password varchar (100) null, sex bit null, DeptId varchar (100) null, CreateDate datetime null, Status int null, SizeId varchar (100) not null, Visible bit null, constraint PK_USER primary key (UserId) GoView Code
9. Application
The following program uses the above framework to write an add data program.
Private void button#click (object sender, EventArgs e) {var bll = new UserBLL (); var p = new UserDefinition (); p. userId = Guid. newGuid (). toString (); p. name = Guid. newGuid (). toString (); p. sizeId = Guid. newGuid (). toString (); p. createDate = DateTime. now; bll. add (p );}View Code
10. intractable diseases
The EF application has been completed. With the above code, we can use EF to access the database. If there is another ray. If you copy the above Code directly to the Project for execution, it may cause a very inexplicable error, that is, an EF assembly is not output to the JZAPP output directory.
When EF6 is installed in the project, two assemblies are added to the project: EntityFramework and EntityFramework. Sqlserver. Our solution. The Model and BLL projects reference EntityFramework and EntityFramework. Sqlserver; JZAPP also references Model and BLL. JZAPP does not directly reference EntityFramework and EntityFramework. Sqlserver. After the solution is compiled, the output directories of the Model and BLL projects include EntityFramework and EntityFramework. Sqlserver assembly. The output directory of the JZAPP project contains only one EntityFramework assembly. The project can be compiled successfully, but an error occurs during running. This problem is confusing at the beginning. Later, I saw a blog with the help of my friends. There is a sentence in it (indirectly referencing the Assembly, if it is just referenced but not called, the Assembly will not be output to the target directory) to let me know the reason. The test result is correct. The solution is to call the program in this set in the program. As follows:
Using Model; using System. data. entity. sqlServer; namespace BLL {public class UserBLL: ParentBLL <UserDefinition> {private string UserName () {using (var bll = new BaseBLL () {return SqlFunctions. userName ();}}}}View Code
Just find a place to write a useless function. After testing, this method can be compiled and solved. However, an error occurs during the call. It doesn't matter. Just solve the problem. How to Use the SqlFunctions class.
It seems that there are other better ways to solve this problem. If you know, please let me know. Thank you.