天天看點

Entity Framework的一個執行個體

Entity Framework的一個執行個體

環境:Visual studio2013+sql server本地資料庫

建立一個C#應用程式,首先在nuget中添加Entity Framework

接下來的工作分為四個主要部分:

第一部分:App.config

這個檔案在建立時會自動生成,我們要做的是在其中增加一個代表資料庫連接配接字元串的标簽

格式:

<connectionStrings>
<add name="CodeFirstDemo" connectionString="Server=DESKTOP-NJVJDDB;Database=mydatabase01;IntegratedSecurity=SSPI" providerName="System.Data.SqlClient"/>
</connectionStrings>
           

添加到<configuration>标簽下

格式的解釋:

在<connectionStrings>中有一些固定的屬性值,可以看定義了解。其中必須的為name屬性和connectionString屬性,其餘屬性均為可選項

name:代表這個<connectionStrings>的名字,主要作用是在其他地方引用時使用

connectionString:用于配置和資料庫的連接配接。主要有三個屬性:

  • DataSource(Server):資料庫伺服器名
  • InitialCatalog(Database):伺服器中的資料庫名
  • IntegratedSecurity:安全政策,有五個值:true/yes/false/no/SSIP,其中SSIP和true的含義是一樣的,都是指将安全政策設定為Windows身份驗證,這時設定的user id和password将不起作用。否則将是用使用者名和密碼登陸資料庫的安全政策

第二部分:實體類檔案

這是一系列C#類檔案,和資料庫的表對應,其中的屬性對應于表的屬性,用于在工作空間中存儲資料,在最終生成程式時會根據這個生成表

值得注意的是,資料庫在建立表時主鍵會預設為自增,這時插入資料會自動生成主鍵值,插入主鍵會導緻異常,要設定為非自增才可以自主設定主鍵

在實體類的主鍵前加入:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;//設定生成表屬性使用的命名空間

namespace MiniProfilerDemo.Models
{
    public class Install
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]//這是設定不自動增長的語句
        public int ID { get; set; }
        public string City { get; set; }
        public string Type { get; set; }

        public Install(int ID,string City,string Type)
        {
            this.ID = ID;
            this.City = City;
            this.Type = Type;
        }
        public Install() { }
    }
}
           

第三部分:Context檔案

這個檔案是要自己建立一個C#類檔案

繼承自DbContext類,這個類是用于連接配接資料庫和程式的中介,用于查詢資料庫或是将更改組合成一個單元再寫回資料庫

A DbContext instance represents acombination of the Unit Of Work and Repository patterns such that it can beused to query from a database and group together changes that will then bewritten back to the store as a unit. 

構造函數:在建立這個類的時候建立對資料庫的連接配接,調用其父類(DbContext)的構造方法:

//public DbContext(stringnameOrConnectionString);

/*Constructs a new context instance using the given string as the name or connection string 
for the database to which aconnection will be made. 
See the class remarks for how this is used to create a connection.*/
//如:
public EFDbContext() : base("name =ASimpleDB") { }
           

參數用于索引在App.config添加的資料庫連接配接字元串

資料(DBSET):

由如下的屬性組成,T表示實體類名,這些屬性組成DbContext代表的資料庫

public DbSet<T> T { get; set; }…
           

Mapper類添加:如果在程式中還添加了Mapper類檔案,那麼就要在這裡将類檔案加入到Context檔案中。這個部分不是必要的

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Configurations.Add(new InstallMapper());//添加映射,InstallMapper就是我添加的Mapper類檔案
}//映射
           

我的Context檔案示例:

//DbContext資料庫上下文,定義了從實體對象到資料庫的映射,從資料庫中檢索資料,就要使用它。
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//我的程式的命名空間
using MiniProfilerDemo.Models;
using MVCDemo.Mapper;
namespace MiniProfilerDemo.DAL
{
    public class EFDbContext : DbContext//繼承自DbContext
    {
        //構造函數: public DbContext(string nameOrConnectionString);
        //base調用基類構造函數,參數為nameOrConnectionString
        //本函數使用的是ConnectingString,位置在Web.config
        //name是指這個連接配接的名字
        public EFDbContext() : base("name = ASimpleDB") { }

        //添加實體類,表示工作空間的資料區
        #region DBSET
        public DbSet<Install> Install { get; set; }
        #endregion

        //添加Mapper類,将資料庫映射到類
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new InstallMapper());//添加映射
        }//映射
    }//class
}
           

第四部分:控制邏輯

既然是一個簡單的執行個體,那麼就在自動生成的主程式入口program.cs中添加控制邏輯

在執行之前需要建立一個DbContext類,并以此類來操作

需要注意的是,在執行對資料庫的修改操作之後還要調用.SaveChanges()方法來儲存更改

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//我的程式的命名空間
using CodeFirstDemo.Model;
namespace CodeFirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new CodeFirstContext())//建立一個context對象
            {
                context.Database.CreateIfNotExists();//如果資料庫不存在時則建立
                TRoles t = new TRoles();
                t.Id = 1;
                t.RoleName = "aa";
                context.Roles.Add(t);//在Roles表中添加條目
                context.SaveChanges();//儲存添加
            }
            Console.Write("DB has Created!");//提示DB建立成功
            Console.Read();
        }//Main
    }//class Program
}//namespace
           

(可選)第五部分:Mapper檔案

設定Mapper類,每一個實體類對應一個Mapper類

繼承自EntityTypeConfiguration<實體類名>

在其中建立無參的構造函數,在其中進行對應的實體類和資料庫表的映射。用其父類的方法來設定映射的表、屬性和設定主鍵等

如:this.ToTable(“表名”):将這個實體類映射到資料庫的參數代表的表

需要注意的是:

Mapper檔案中的this.ToTable();方法有兩種

//第一種:代表的資料庫名:tableName

public EntityTypeConfiguration<TEntityType>ToTable(string tableName);

//第二種:這種代表的資料庫名會有一個字首即 schemeName.tableName

public EntityTypeConfiguration<TEntityType>ToTable(string tableName, string schemaName);
           

示例:

using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
//我的程式的命名空間
using MiniProfilerDemo.Models;
namespace MVCDemo.Mapper
{
    internal class InstallMapper : EntityTypeConfiguration<Install>
    {
        internal InstallMapper()
        {
            this.ToTable("Install");
            this.HasKey(t => t.ID );

            this.Property(t => t.ID).HasColumnName("ID");
            this.Property(t => t.City).HasColumnName("City");
            this.Property(t => t.Type).HasColumnName("Type");
        }
    }
}
           

源碼:

https://github.com/biaoJM/ASP.NET-MVC-DEMO/tree/master/MVCDemo/MVCDemo

繼續閱讀