Simple to use C # EF's

First, access to EF

 1. Open NuGet Package Manager Console

 2. Select the default items (items to be imported EF), enter the command: Install-Package EntityFramework

3. If the import is successful, there will be the following two references in the References

Second, adding Entity Data Model 

 1. Add New Item, select the ADO.NET Entity Data Model

 2. Select Code First (the other two modes may be selected and DB First Model First)

ps: the difference between the three is recommended Bowen: https://blog.csdn.net/u010191243/article/details/44755977?utm_source=copy

 3. Select the model to create a database, the connection string can be generated automatically or manually selected settings

4. Select the model to generate tables and views 

 The project will automatically generate a file DbContext derived model class and each table

 

Brief three generated files 

1. Database table information 

CREATE TABLE [dbo].[T_EF]
(
	[ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL primary key,
	[Name] [nchar](10) NULL,
	[Age] [tinyint] NULL,
	[Location] [nchar](10) NULL
)

2. DbContext

namespace EFConsole
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;

    public partial class BridgeContext : DbContext
    {
        /// <summary>
        /// 利用连接字符串连接数据库
        /// </summary>
        public BridgeContext(string connStr) : base(connStr)
        {
        }

        /// <summary>
        /// 利用App.config中配置的字符串连接数据库
        /// </summary>
        public BridgeContext() : base("name=BridgeDb")
        {
        }

        public virtual DbSet<T_EF> T_EF { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<T_EF>()
                .Property(e => e.ID)
                .HasPrecision(18, 0);

            modelBuilder.Entity<T_EF>()
                .Property(e => e.Name)
                .IsFixedLength();

            modelBuilder.Entity<T_EF>()
                .Property(e => e.Location)
                .IsFixedLength();
        }
    }
}

3.App.config file 

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <!--选择生成带密码时的连接字符串-->
    <add name="BridgeDb" connectionString="Server=.;Initial Catalog=Bridge;User ID=sa;Password=123" providerName="System.Data.SqlClient" />
    <!--选择生成不带密码时的连接字符串-->
    <add name="BridgeContext" connectionString="data source=PC-20181123XOVS\BRIDGE;initial catalog=Bridge;persist security info=True;user id=sa;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

4. table file 

namespace EFConsole
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    /// <summary>
    /// 指定表名
    /// </summary>
    [Table("T_EF")]
    public class T_EF
    {
        /// <summary>
        /// [主键(每个表必须要有主键),表示是自增列]
        /// </summary>
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public decimal ID { get; set; }

        /// <summary>
        /// [指定对应的列名,限定列的字符长度]
        /// </summary>
        [Column("Name"), StringLength(10)]
        public string Name { get; set; }

        /// <summary>
        /// 可空类型指定
        /// </summary>
        public byte? Age { get; set; }

        [StringLength(10)]
        public string Location { get; set; }
    }
}

Fourth, additions and deletions to the database change search 

1. increase 

using (var bridgeContext = new BridgeContext())
{
    //添加一个对象
    T_EF t_EF = bridgeContext.T_EF.Add(new T_EF() { Name = "RB" });
    //将修改后的保存到数据库
    bridgeContext.SaveChanges();
}

2. Check 

//根据主键查询
T_EF t_EF1 = bridgeContext.T_EF.Find(1);
//根据TSQL查询
DbSqlQuery<T_EF> dbSqlQuery = bridgeContext.T_EF.SqlQuery("select * from [T_EF] where [ID] = {0}", 2);

3. change 

//修改数据,需先查出实体,再修改保存
T_EF t_EF1 = bridgeContext.T_EF.Find(1);
t_EF1.Location = "GD";
bridgeContext.SaveChanges();

4. deleted 

//删除数据也需先查出后删除再保存
DbSqlQuery<T_EF> dbSqlQuery = bridgeContext.T_EF.SqlQuery("select * from [T_EF] where [ID] = {0}", 2);
bridgeContext.T_EF.RemoveRange(dbSqlQuery);
bridgeContext.SaveChanges();

 

 

 

 

 

 

 

 

 

 

 

 

 

Published 31 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/breakbridge/article/details/104510572