星期日, 1月 20, 2019

[EF] Connection

第一次操作 EF,簡易記錄操作過程

利用 nuget 先安裝 Entity Frameworks

[EF] Connection-1

建立 ADO.NET 實體資料模型

[EF] Connection-2


選擇來自資料庫的 Code First

[EF] Connection-3

選擇連線

[EF] Connection-4

選擇資料表 Person.Person Table

[EF] Connection-5

ADO.NET 實體資料模型建立後,會產生 AdventureWorksContext.cs、Person.cs、App.Config 內會有 EF 相關設定和連線字串

[EF] Connection-6

App.Config 檔案內容
<?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>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="AdventureWorksContext" connectionString="data source=.\SQL2017;initial catalog=AdventureWorks;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>
AdventureWorksContext.cs
namespace EFConnection
{
    using System.Data.Entity;

    // 繼承 DbContext
    public partial class AdventureWorksContext : DbContext
    {
        public AdventureWorksContext()
            // App.config 內的連線字串名稱
            : base("name=AdventureWorksContext")
        {
        }

        // Person 資料集
        public virtual DbSet<Person> Person { get; set; }

        // Fluent API 來定義
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Person>()
                .Property(e => e.PersonType)
                .IsFixedLength();
        }
    }
}
Person.cs
namespace EFConnection
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("Person.Person")]
    public partial class Person
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int BusinessEntityID { get; set; }

        [Required]
        [StringLength(2)]
        public string PersonType { get; set; }

        public bool NameStyle { get; set; }

        [StringLength(8)]
        public string Title { get; set; }

        [Required]
        [StringLength(50)]
        public string FirstName { get; set; }

        [StringLength(50)]
        public string MiddleName { get; set; }

        [Required]
        [StringLength(50)]
        public string LastName { get; set; }

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

        public int EmailPromotion { get; set; }

        [Column(TypeName = "xml")]
        public string AdditionalContactInfo { get; set; }

        [Column(TypeName = "xml")]
        public string Demographics { get; set; }

        public Guid rowguid { get; set; }

        public DateTime ModifiedDate { get; set; }

        // 自行 override,方便資料輸出而已
        public override string ToString()
        {
            return $"{LastName}-{FirstName}";
        }

    }
}
測試 Code
namespace EFConnection
{
    class Program
    {
        static void Main(string[] args)
        {
            var context = new AdventureWorksContext();

            // 在每一次 DbContext 物件運行的過程中,每一段 TSQL 均會在主控台輸出
            context.Database.Log = Console.Write;

            // 顯示連線字串
            Console.WriteLine("----- 顯示連線字串 -----");
            Console.WriteLine(context.Database.Connection.ConnectionString);

            var Data = context.Person.Where(w => w.LastName
                .Substring(0, 1) == "L")
                .Take(10);

            // 顯示 TSQL 語法
            Console.WriteLine("");
            Console.WriteLine("----- 顯示 TSQL 語法 -----");
            Console.WriteLine(Data.ToString());

            // 顯示 10 筆資料
            Console.WriteLine("");
            Console.WriteLine("----- 顯示資料 -----");
            foreach (var item in Data)
            {
                Console.WriteLine(item);
            }
        }
    }
}
沒有開啟 Log 的簡易輸出結果

[EF] Connection-7

沒有留言:

張貼留言