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");
        }
    }
}





猜你喜欢

转载自blog.csdn.net/qq_40711741/article/details/80998151
今日推荐