Entity?Framework代碼優(yōu)先(Code?First)模式
一、Code First 代碼優(yōu)先
DbContext可以用于數(shù)據(jù)庫優(yōu)先,代碼優(yōu)先和模型優(yōu)先的開發(fā)。
DbContext主要包含一組非常易于使用的API。該API由ObjectContext公開。這些API還允許我們使用ObjectContext不允許的Code First方法。
DbContext只是ObjectContext包裝器,可以說它是ObjectContext的輕量級替代方案。
1、從ObjectContext轉(zhuǎn)化到DbContext
DbContext ctx= new DbContext(ctxObj , true);
EF6支持Oracle ODT 12C Release 3 (net4.5)以上
二、創(chuàng)建或生成Model代碼
1、從數(shù)據(jù)庫生成Model代碼
可以使用高級的反向工程工具POCO生成器模板(收費)。https://marketplace.visualstudio.com/items?itemName=SimonHughes.EntityFrameworkReversePOCOGenerator
一般使用Visual Studio EF 6工具附帶的不太高級的“"Code First from Database" ”功能。
實體框架提供了一種對現(xiàn)有數(shù)據(jù)庫使用代碼優(yōu)先方法的簡便方法。它將為現(xiàn)有數(shù)據(jù)庫中的所有表和視圖創(chuàng)建實體類,并使用數(shù)據(jù)注釋屬性和Fluent API對其進行配置。
要將代碼優(yōu)先用于現(xiàn)有數(shù)據(jù)庫,請在Visual Studio中右鍵單擊您的項目->添加->新建項。
在“添加新項”對話框中選擇“ADO.NET實體數(shù)據(jù)模型”,并指定模型名稱(這將是上下文類名稱),然后單擊“添加”。
這將打開“實體數(shù)據(jù)模型”向?qū)В缦滤?。從?shù)據(jù)庫選項中選擇代碼優(yōu)先,然后單擊下一步。
現(xiàn)在,為現(xiàn)有數(shù)據(jù)庫選擇數(shù)據(jù)連接。如果下拉列表不包括與現(xiàn)有數(shù)據(jù)庫的連接,請為您的數(shù)據(jù)庫創(chuàng)建一個新連接。單擊下一步繼續(xù)。
現(xiàn)在,選擇要為其生成類的表和視圖,然后單擊“完成”。
這將為您的數(shù)據(jù)庫表和視圖生成所有實體類,如下所示。
例如,它將創(chuàng)建以下上下文類,該上下文類使用Fluent API根據(jù)數(shù)據(jù)庫配置實體類。
namespace EFDemo { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; public partial class SchoolContext : DbContext { public SchoolContext() : base("name=SchoolContext2") { } public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Standard> Standards { get; set; } public virtual DbSet<Student> Students { get; set; } public virtual DbSet<StudentAddress> StudentAddresses { get; set; } public virtual DbSet<Teacher> Teachers { get; set; } public virtual DbSet<View_StudentCourse> View_StudentCourse { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Course>() .Property(e => e.CourseName) .IsUnicode(false); modelBuilder.Entity<Course>() .HasMany(e => e.Students) .WithMany(e => e.Courses) .Map(m => m.ToTable("StudentCourse").MapLeftKey("CourseId").MapRightKey("StudentId")); modelBuilder.Entity<Standard>() .Property(e => e.StandardName) .IsUnicode(false); modelBuilder.Entity<Standard>() .Property(e => e.Description) .IsUnicode(false); modelBuilder.Entity<Standard>() .HasMany(e => e.Students) .WithOptional(e => e.Standard) .WillCascadeOnDelete(); modelBuilder.Entity<Standard>() .HasMany(e => e.Teachers) .WithOptional(e => e.Standard) .WillCascadeOnDelete(); modelBuilder.Entity<Student>() .Property(e => e.StudentName) .IsUnicode(false); modelBuilder.Entity<Student>() .Property(e => e.RowVersion) .IsFixedLength(); modelBuilder.Entity<Student>() .HasOptional(e => e.StudentAddress) .WithRequired(e => e.Student) .WillCascadeOnDelete(); modelBuilder.Entity<StudentAddress>() .Property(e => e.Address1) .IsUnicode(false); modelBuilder.Entity<StudentAddress>() .Property(e => e.Address2) .IsUnicode(false); modelBuilder.Entity<StudentAddress>() .Property(e => e.City) .IsUnicode(false); modelBuilder.Entity<StudentAddress>() .Property(e => e.State) .IsUnicode(false); modelBuilder.Entity<Teacher>() .Property(e => e.TeacherName) .IsUnicode(false); modelBuilder.Entity<Teacher>() .HasMany(e => e.Courses) .WithOptional(e => e.Teacher) .WillCascadeOnDelete(); modelBuilder.Entity<View_StudentCourse>() .Property(e => e.StudentName) .IsUnicode(false); modelBuilder.Entity<View_StudentCourse>() .Property(e => e.CourseName) .IsUnicode(false); } } }
EF 6有用的設計時實用程序:https://marketplace.visualstudio.com/items?itemName=ErikEJ.EntityFramework6PowerToolsCommunityEdition
2、手工創(chuàng)建Model代碼
方式1、使用標注
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace CodeFirst.Model { /// /// 目的景點類 /// [Table("DESTINATIONS", Schema = "PAMS")] public class Destination { [Column("DESTINATIONID", TypeName = "INT")] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int DestinationId { get; set; } [Column("NAME")] public string Name { get; set; } [Column("COUNTRY")] public string Country { get; set; } [Column("DESCRIPTION")] public string Description { get; set; } [Column("PHOTO")] public byte[] Photo { get; set; } public virtual List Lodgings { get; set; } //景點帶有多個住宿點 } /// /// 住宿類 /// [Table("LODGINGS", Schema = "PAMS")] public class Lodging { [Column("LODGINGID", TypeName = "INT")] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int LodgingId { get; set; } [Column("NAME")] public string Name { get; set; } [Column("OWNER")] public string Owner { get; set; } [Column("TARDESTINATIONID", TypeName = "INT")] public int? DestinationID { get; set; } [ForeignKey("DestinationID")] public Destination Destination { get; set; } } /// /// 度假村類,繼承自住宿類 /// public class Resort : Lodging { [Column("ENTERTAINMENT")] public string Entertainment { get; set; } } /// /// 旅館類,繼承自住宿類 /// public class Hostel : Lodging { [Column("MAXROOM", TypeName = "INT")] public int? MaxRoom { get; set; } } }
方式2:使用模板Builder“配置”屬性和關(guān)系
using CodeFirst.Model; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; namespace CodeFirst.DataAccess { public class BreakAwayContext : DbContext { public DbSet Destinations { get; set; } public DbSet Lodgings { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new DestinationMap()); modelBuilder.Configurations.Add(new LodgingMap()); } } public class DestinationMap : EntityTypeConfiguration { public DestinationMap() { this.HasKey(t => t.DestinationId); Property(d => d.Name).IsRequired(); Property(d => d.Description).HasMaxLength(500); } } public class LodgingMap : EntityTypeConfiguration { public LodgingMap() { this.HasKey(t => t.LodgingId); Property(d => d.Name).IsRequired(); Property(d => d.Owner).HasMaxLength(500); this.Map(d => d.Requires("TYPE").HasValue("Standard")); this.Map(d => d.Requires("TYPE").HasValue("Resort")); this.Map(d => d.Requires("TYPE").HasValue("Hostel")); } } }
三、配置文件
<connectionStrings> <add name="BreakAwayContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=BreakAway;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient"/> </connectionStrings>
四、操作
1、添加單個實體,Add
var destination = new CodeFirst.Model.Destination { Country = "Indonesia", Description = "EcoTourism at its best in exquisite Bali", Name = "Bali" }; using (var context = new CodeFirst.DataAccess.BreakAwayContext()) { if (context.Destinations.Count((t => t.Name == "Bali") < 1) { context.Destinations.Add(destination); context.SaveChanges(); } }
2、修改
using (var context = new CodeFirst.DataAccess.BreakAwayContext()) { var canyon = (from d in context.Destinations where d.Name == "Bali" select d).Single(); canyon.Description = "227 mile long canyon."; //context.Entry(canyon )=EntityState.Modified; context.SaveChanges(); }
3、刪除,Remove
var toDelete = new CodeFirst.Model.Destination { Name = "Bali" }; context.Destinations.Attach(toDelete); //attach context.Destinations.Remove(toDelete); context.SaveChanges();
五、查詢
1、Load():
把數(shù)據(jù)加載到內(nèi)存,使用實體的Local屬性訪問。(LINQ寫法,同foreach)
using (var context = new CodeFirst.DataAccess.BreakAwayContext()) { var query = from d in context.Destinations where d.Country == "Australia" select d; query.Load();// foreach 也可以 var count = context.Destinations.Local.Count; }
2、ToList():
一次性從數(shù)據(jù)庫中查出數(shù)據(jù)
var Invoices=ctx.Invoie.ToList(); foreach(var result in Onvoices) {.}
3、Find():
根據(jù)鍵值先從內(nèi)存中查詢,內(nèi)存中沒有才查詢數(shù)據(jù)庫。
var destination = context.Destinations.Find(4);
4、Single()、SingleOrDefault()、First()等:
可根據(jù)條件直接從數(shù)據(jù)庫查。
var destination = context.Destinations.SingleOrDefault(d => d.Name == "Bali");
六、直接執(zhí)行SQL語句
1、在實體上運行SQL命令,
SQL查詢:SqlQuery
DbSqlQuery c = ctx.Lodging.SqlQuery("select * from.."); //EF跟蹤返回的對象。
2、在Database屬性上運行SQL命令
1、SQL查詢:Database.SqlQuery
IEnumerable a = ctx.Database.SqlQuery("Select * from.."); //可直接轉(zhuǎn)為定義的實體類型,任何類型,EF不跟蹤
2、執(zhí)行SQL命令:Database.ExecuteSqlCommand
ctx.Database.ExecuteSqlCommand("delete from pams.DESTINATIONS where Name='Bali'");//直接執(zhí)行sql
到此這篇關(guān)于Entity Framework代碼優(yōu)先(Code First)的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- Entity Framework使用Code First模式管理事務
- Entity Framework使用Code First模式管理存儲過程
- Entity Framework使用Code First模式管理視圖
- Entity?Framework使用Code?First的實體繼承模式
- Entity Framework使用Code First模式管理數(shù)據(jù)庫
- EF使用Code First模式生成單數(shù)形式表名
- EF使用Code First模式給實體類添加復合主鍵
- 使用EF的Code?First模式操作數(shù)據(jù)庫
- C#筆記之EF Code First 數(shù)據(jù)模型 數(shù)據(jù)遷移
- Entity?Framework代碼優(yōu)先Code?First入門
相關(guān)文章
C# Entity Framework中的IQueryable和IQueryProvider詳解
這篇文章主要介紹了C# Entity Framework中的IQueryable和IQueryProvider詳解,本文使用實例分析這兩個接口的內(nèi)部實現(xiàn),需要的朋友可以參考下2015-01-01