Someone may ask why I want to use EF to create a data table that loves you. What are the benefits of code first?
When using EF to create a database or table, you only need to design a simple C # class. When the table content changes, it automatically updates the database structure and retains the original data.
EF is very powerful. It supports primary and Foreign keys and can generate the same data type as in dB. Since these two tables are simple, I will put the advanced knowledge at the bottom of this article as an appendix.
We have two input files as needed. One is trend and the other is bar. Let's take a look at the data in these two files:
Trend:
id taskid taskname time b1 equal b2 uncertain grandtotal 0 1 task1 2012-6-27 200 300 280 220 1000
Bar:
Keyword b1better equal b2better winner join crowd 2 0 3 0 0 B1 crazy countdown 0 0 3 0 0 B2 Zhang Nala 0 1 1 2 2 0 B1 software 1 0 1 1 2 B2
We need to show 2 charts.
Then we design two tables to store the data of the trend chart and barchart, named trend and bar (Originally three tables. Because we designed two exercises for ourselves .)
So far, I found that we have not named our project. What's better? Let's call it reportingsyncer.
Reporting (report), sync (synchronization), why add er? Currently, Project names are often anthropomorphic, Which is vivid and powerful.
[Start]
Open vs 2010 and create a new class library named reportingdbmanager. Delete automatically generated class1.cs.
Modify the SLN (solution name: reportingsyncer ).
Modify the namespace: Right-click reportingdbmanager. Properties-> application: cnblogsdemos. reportingdbmanager. Why? Because it is easier to reference and professional :)
Now your SLN should be like this
Add an Entity Framework reference to obtain the DLL in two ways:
Use nuget or download a DLL. Here I use nuget. The latest version of EF is 4.3.1.
[Create a table ing Class]
After adding the reference, we will start to create our table class.
Add two classes named trend and bar.
For the above input file type, we design two matching tables.
Bar. CS:
Namespace cnblogsdemos. reportingdbmanager {using system. componentmodel; using system. componentmodel. dataannotations; public class bar {[Key] [databasegenerated (databasegeneratedoption. identity)] // primary key auto-increment public int ID {Get; set;} public int taskid {Get; set;} [maxlength (200)] Public String taskname {Get; set;}/* Some friends have asked, why do they need to be set when there are no above two fields in the import file? Because the data is imported according to each task during the import process, we can associate the two tables with the data task id and task name in CommandLine. the drill down (drill-in) of the report can be implemented later) */[maxlength (500)] Public String keyword {Get; set;} public int b1better {Get; set;} public int equal {Get; set ;} public int b2better {Get; set;} [maxlength (50)] Public String winner {Get; set;} public string type {Get; set;} [defaultvalue (true)] public bool isactive {Get; Set ;}}}
Trend. CS
namespace CnBlogsDemos.ReportingDBManager{ using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; public class Trend { public int id { get; set; } public int TaskID { get; set; } public string TaskName { get; set; } public DateTime Time { get; set; } public int B1Better { get; set; } public int Equal { get; set; } public int B2Better { get; set; } public int UnCertain { get; set; } public int GrandTotal { get; set; } [MaxLength(50)] public string type { get; set; } [DefaultValue(true)] public bool IsActive { get; set; } }}
The two table classes have been created. How can I contact a database? We need to use EF to create a dbcontext class.
Add new class: dbstorecontext. CS
namespace CnBlogsDemos.ReportingDBManager{ using System.Data.Entity; using System.Data.Entity.Migrations; internal sealed class ReportingDbMigrationsConfiguration : DbMigrationsConfiguration<DbStoreContext> { public ReportingDbMigrationsConfiguration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; } } public class DbStoreContext : DbContext { public DbStoreContext() : base("name=ReportingDataBase") { Database.SetInitializer<DbStoreContext>( new MigrateDatabaseToLatestVersion<DbStoreContext, ReportingDbMigrationsConfiguration>()); this.Configuration.LazyLoadingEnabled = false; } public DbSet<Bar> Bars { get; set; } public DbSet<Trend> Trends { get; set; } }}
The two dbsets above are the two tables we want to create.
Check the app. config file in the project. We will see:
<entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"> <parameters> <parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" /> </parameters> </defaultConnectionFactory> </entityFramework>
By default, EF specifies a local express database. We can change it to another standard database or remote database (of course, you must have the permission ).
We want to specify the database connection in another project. Delete this appconfig first.
Some friends have asked, when can I generate dB and table? Why can't I see it?
Don't worry. It will be created/updated when we call this dbcontext class for the first time!
I will explain it in the next chapter.
[Appendix]
EF has some tips for table creation. I have checked a lot of information and hope to help you:
Primary key:
[Key]public int EngineID { get; set; }
Auto-increment primary key:
[Key,DatabaseGenerated(DatabaseGeneratedOption.None)]public int EngineID { get; set; }
Primary key that can be edited (readonly by default)
[Key,Editable(true),DatabaseGenerated(DatabaseGeneratedOption.None)]public int EngineID { get; set; }
Non-empty field:
[Required] public string EngineName { get; set; }
Non-empty fields with limited length:
[Required, MaxLength(256)] public string EngineName { get; set; }
Foreign keys are special. You need to explain the relationship between the two tables.
Table1 contains a field taskid.
The primary key of table task is taskid. You need to create a field of the task type that loves you. The link is as follows:
public class Table1{ [Required, ForeignKey("Task")] public int TaskID { get; set; } public virtual Task Task { get; set; }}public class Task{ [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int TaskID { get; set; }}
Timestamp:
[ConcurrencyCheck] 1544158309 public byte[] TimeStamp { get; set; }
Int32 in C # Corresponds to int in dB. Int16 corresponds to smallint, bool corresponds to bit, byte [] corresponds to binary, and so on.