Entity?Framework代碼優(yōu)先(Code?First)模式
一、Code First 代碼優(yōu)先
DbContext可以用于數(shù)據(jù)庫(kù)優(yōu)先,代碼優(yōu)先和模型優(yōu)先的開(kāi)發(fā)。
DbContext主要包含一組非常易于使用的API。該API由ObjectContext公開(kāi)。這些API還允許我們使用ObjectContext不允許的Code First方法。
DbContext只是ObjectContext包裝器,可以說(shuō)它是ObjectContext的輕量級(jí)替代方案。
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ù)庫(kù)生成Model代碼
可以使用高級(jí)的反向工程工具POCO生成器模板(收費(fèi))。https://marketplace.visualstudio.com/items?itemName=SimonHughes.EntityFrameworkReversePOCOGenerator
一般使用Visual Studio EF 6工具附帶的不太高級(jí)的“"Code First from Database" ”功能。
實(shí)體框架提供了一種對(duì)現(xiàn)有數(shù)據(jù)庫(kù)使用代碼優(yōu)先方法的簡(jiǎn)便方法。它將為現(xiàn)有數(shù)據(jù)庫(kù)中的所有表和視圖創(chuàng)建實(shí)體類(lèi),并使用數(shù)據(jù)注釋屬性和Fluent API對(duì)其進(jìn)行配置。
要將代碼優(yōu)先用于現(xiàn)有數(shù)據(jù)庫(kù),請(qǐng)?jiān)赩isual Studio中右鍵單擊您的項(xiàng)目->添加->新建項(xiàng)。

在“添加新項(xiàng)”對(duì)話(huà)框中選擇“ADO.NET實(shí)體數(shù)據(jù)模型”,并指定模型名稱(chēng)(這將是上下文類(lèi)名稱(chēng)),然后單擊“添加”。

這將打開(kāi)“實(shí)體數(shù)據(jù)模型”向?qū)?,如下所示。從?shù)據(jù)庫(kù)選項(xiàng)中選擇代碼優(yōu)先,然后單擊下一步。

現(xiàn)在,為現(xiàn)有數(shù)據(jù)庫(kù)選擇數(shù)據(jù)連接。如果下拉列表不包括與現(xiàn)有數(shù)據(jù)庫(kù)的連接,請(qǐng)為您的數(shù)據(jù)庫(kù)創(chuàng)建一個(gè)新連接。單擊下一步繼續(xù)。

現(xiàn)在,選擇要為其生成類(lèi)的表和視圖,然后單擊“完成”。

這將為您的數(shù)據(jù)庫(kù)表和視圖生成所有實(shí)體類(lèi),如下所示。

例如,它將創(chuàng)建以下上下文類(lèi),該上下文類(lèi)使用Fluent API根據(jù)數(shù)據(jù)庫(kù)配置實(shí)體類(lèi)。
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有用的設(shè)計(jì)時(shí)實(shí)用程序:https://marketplace.visualstudio.com/items?itemName=ErikEJ.EntityFramework6PowerToolsCommunityEdition

2、手工創(chuàng)建Model代碼
方式1、使用標(biāo)注
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace CodeFirst.Model
{
///
/// 目的景點(diǎn)類(lèi)
///
[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; } //景點(diǎn)帶有多個(gè)住宿點(diǎn)
}
///
/// 住宿類(lèi)
///
[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; }
}
///
/// 度假村類(lèi),繼承自住宿類(lèi)
///
public class Resort : Lodging
{
[Column("ENTERTAINMENT")]
public string Entertainment { get; set; }
}
///
/// 旅館類(lèi),繼承自住宿類(lèi)
///
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、添加單個(gè)實(shí)體,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();五、查詢(xún)
1、Load():
把數(shù)據(jù)加載到內(nèi)存,使用實(shí)體的Local屬性訪(fǎng)問(wèn)。(LINQ寫(xiě)法,同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ù)庫(kù)中查出數(shù)據(jù)
var Invoices=ctx.Invoie.ToList();
foreach(var result in Onvoices)
{.}3、Find():
根據(jù)鍵值先從內(nèi)存中查詢(xún),內(nèi)存中沒(méi)有才查詢(xún)數(shù)據(jù)庫(kù)。
var destination = context.Destinations.Find(4);
4、Single()、SingleOrDefault()、First()等:
可根據(jù)條件直接從數(shù)據(jù)庫(kù)查。
var destination = context.Destinations.SingleOrDefault(d => d.Name == "Bali");
六、直接執(zhí)行SQL語(yǔ)句
1、在實(shí)體上運(yùn)行SQL命令,
SQL查詢(xún):SqlQuery
DbSqlQuery c = ctx.Lodging.SqlQuery("select * from.."); //EF跟蹤返回的對(duì)象。2、在Database屬性上運(yùn)行SQL命令
1、SQL查詢(xún):Database.SqlQuery
IEnumerable a = ctx.Database.SqlQuery("Select * from.."); //可直接轉(zhuǎn)為定義的實(shí)體類(lèi)型,任何類(lèi)型,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)的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Entity Framework使用Code First模式管理事務(wù)
- Entity Framework使用Code First模式管理存儲(chǔ)過(guò)程
- Entity Framework使用Code First模式管理視圖
- Entity?Framework使用Code?First的實(shí)體繼承模式
- Entity Framework使用Code First模式管理數(shù)據(jù)庫(kù)
- EF使用Code First模式生成單數(shù)形式表名
- EF使用Code First模式給實(shí)體類(lèi)添加復(fù)合主鍵
- 使用EF的Code?First模式操作數(shù)據(jù)庫(kù)
- C#筆記之EF Code First 數(shù)據(jù)模型 數(shù)據(jù)遷移
- Entity?Framework代碼優(yōu)先Code?First入門(mén)
相關(guān)文章
C#實(shí)現(xiàn)日期操作類(lèi)DateTime的方法示例
C#中日期和時(shí)間操作主要通過(guò)System.DateTime類(lèi)實(shí)現(xiàn),提供了創(chuàng)建、格式化、比較和計(jì)算等功能,下面就來(lái)具體介紹一下,感興趣的可以了解一下2025-03-03
C# ODP.NET 調(diào)用Oracle函數(shù)返回值時(shí)報(bào)錯(cuò)的一個(gè)解決方案
這篇文章主要介紹了C# ODP.NET 調(diào)用Oracle函數(shù)返回值時(shí)報(bào)錯(cuò)的一個(gè)解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12

