Professional Documents
Culture Documents
5
1.1 Tng quan
1.1.1
Gii thiu
Runtime cng thc thi m mnh m bng cch thc hin c s h tng cht ch
v xc nhn m ngun gi l common type system (CTS). CTS m bo rng tt c
cc m qun l t m t (self-describing). S khc nhau trnh bin dch Microsoft v
bn th ba to ra m qun l u ph hp ci CTS. iu ny c ngha rng m qun l
c th s dng cho cc loi qun l, trng hp khc nhau, trong khi thc thi nghim
tc yu t trung thc v an ton.
Ngoi ra, mi trng qun l ca runtime loi b nhiu vn phn mm ph
bin. V d, runtime t ng x l i tng giao din v qun l tham chiu n i
tng, gii phng chng khi khng c s dng li. Qun l b nh t ng x l 2
li ng dng ph bin, r r b nh v tham chiu b nh khng hp l.
Runtime cng tng tc nng sut pht trin. V d, lp trnh vin c th vit
chng trnh trong ngn ng pht trin m h chn, nhng c th tn dng thi
runtime, lp th vin, v thnh phn vit bng ngn ng khc ca nh pht trin khc.
Bt k nh cung cp trnh bin dch la chn mc tiu runtime u c th lm nh vy.
Mc tiu ca trnh bin dch ngn ng ca .NET Framework l lm cho cc tnh nng
sn c ca .NET Framework tn ti m c vit trong ngn ng, gip gim bt qu
trnh chuyn i cho cc ng dng hin c.
Trong khi runtime c thit k cho cc phn mm tng lai, n cng h tr cho
phn mm hin ti v qu kh. Kh nng tng thch gia m qun l v khng qun
l cho php nh pht trin tip tc s dng cc thnh phn COM v DLL cn thit.
Runtime c thit k nng cao hiu sut. Mc d CLR cung cp nhiu dch
v runtime tiu chun, managed code th khng bao gi thng dch. Mt tnh nng gi
l bin dch (JIT) cho php tt c cc m qun l chy bng ngn ng my m n thc
hin trn . Trong khi , qun l b nh loi b kh nng phn mnh b nh v tng
tc truy xut b nh cc b tng hiu sut.
Cui cng, runtime c th lu tr (hosted) bi hiu sut cao, pha my ch ng
dng, nh Microsoft SQL Server v Internet Information Services (IIS). C s h tng
ny cho php bn dng m qun l vit business logic ca bn, trong khi vn tri
nghim hiu sut vt tri ca ngnh cng nghip my ch doanh nghip h tr lu
tr thi gian thc.
4
1.1.3
Ci thin WCF v WF
Tch hp ASP.NET AJAX
Namespace mi System.CodeDom
Microsoft ADO.NET Entity Framework 1.0
Cng nh phin bn 3.0, c th mnh ha s thay i ca .NET 3.5 bng cng
thc:
.NET 3.5 = .NET 3.0 + LINQ + ASP.NET 3.5 + REST
1.2.6
ny gi l .NET cho cc Windows Store app v c tho lun trong phn tng quan
Windows Dev Center.
1.3.2
Project Portable Class Library trong Visual Studio 2012 (hoc cc phin bn sau
ny) cho php bn vit v xy dng managed assemblies lm vic a nn tng .NET
Framework. Dng mt project Portable Class Library, chn nn tng (nh Windows
Phone v .NET cho cc Windows Store app) hng n. Nhng types sn c v cc
member trong project ca bn th t ng gii hn thnh cc common type v member
trn cc nn tng. bit thm chi tit, xem Cross-Platform Development vi .NET
Framework.
1.3.3
Cc yu t mi v ci tin
(IDAN)
trong
lp
10
Tools
Parallel Computing
Web
Networking
15
Windows
Presentation
Foundation
(WPF),
Windows
Li ch ca Entity Framework
Gim thi gia pht trin; framework cung cp kh nng truy cp d liu li
ngi lp trnh c th tp trung vo ng dng logic.
19
<EntityType Name="SinhVien">
<Key>
<PropertyRef Name="MSSV" />
</Key>
<Property Type="Int32" Name="MSSV" Nullable="false"
annotation:StoreGeneratedPattern="Identity" />
<Property Type="String" Name="HoTen" Nullable="false" />
<NavigationProperty Name="LopHoc"
Relationship="Vidu.SinhVienLopHoc"
FromRole="SinhVien" ToRole="LopHoc" />
</EntityType>
<EntityType Name="LopHoc">
<Key>
<PropertyRef Name="MaLop" />
</Key>
<Property Type="Int32" Name="MaLop" Nullable="false"
annotation:StoreGeneratedPattern="Identity" />
<Property Type="String" Name="TenLop" Nullable="false" />
<NavigationProperty Name="SinhVien"
Relationship="Vidu.SinhVienLopHoc"
FromRole="LopHoc" ToRole="SinhVien" />
</EntityType>
<Association Name="SinhVienLopHoc">
<End Type="Vidu.SinhVien" Role="SinhVien" Multiplicity="*" />
<End Type="Vidu.LopHoc" Role="LopHoc" Multiplicity="*" />
</Association>
</Schema>
</edmx:ConceptualModels>
20
21
<EntityType Name="DanhSachSinhVien">
<Key>
<PropertyRef Name="MSSV" />
</Key>
<Property Name="MSSV" Type="int"
StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="HoTen" Type="nvarchar(max)" Nullable="false" />
</EntityType>
<EntityType Name="DanhSachLopHoc">
<Key>
<PropertyRef Name="MaLop" />
</Key>
<Property Name="MaLop" Type="int"
StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="TenLop" Type="nvarchar(max)" Nullable="false" />
</EntityType>
<EntityType Name="SinhVienLopHoc">
<Key>
<PropertyRef Name="SinhVien_MSSV" />
<PropertyRef Name="LopHoc_MaLop" />
</Key>
<Property Name="SinhVien_MSSV" Type="int" Nullable="false" />
<Property Name="LopHoc_MaLop" Type="int" Nullable="false" />
</EntityType>
<Association Name="FK_SinhVienLopHoc_SinhVien">
<End Role="SinhVien"
Type="Vidu.Store.DanhSachSinhVien" Multiplicity="1" />
<End Role="SinhVienLopHoc"
Type="Vidu.Store.SinhVienLopHoc" Multiplicity="*" />
<ReferentialConstraint>
22
<Principal Role="SinhVien">
<PropertyRef Name="MSSV" />
</Principal>
<Dependent Role="SinhVienLopHoc">
<PropertyRef Name="SinhVien_MSSV" />
</Dependent>
</ReferentialConstraint>
</Association>
<Association Name="FK_SinhVienLopHoc_LopHoc">
<End Role="SinhVienLopHoc"
Type="Vidu.Store.SinhVienLopHoc" Multiplicity="*" />
<End Role="LopHoc" Type="Vidu.Store.DanhSachLopHoc" Multiplicity="1" />
<ReferentialConstraint>
<Principal Role="LopHoc">
<PropertyRef Name="MaLop" />
</Principal>
<Dependent Role="SinhVienLopHoc">
<PropertyRef Name="LopHoc_MaLop" />
</Dependent>
</ReferentialConstraint>
</Association>
</Schema></edmx:StorageModels>
23
xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs">
<EntityContainerMapping StorageEntityContainer="ViduStoreContainer"
CdmEntityContainer="ViduContainer">
<EntitySetMapping Name="DanhSachSinhVien">
<EntityTypeMapping TypeName="IsTypeOf(Vidu.SinhVien)">
<MappingFragment StoreEntitySet="DanhSachSinhVien">
<ScalarProperty Name="MSSV" ColumnName="MSSV" />
<ScalarProperty Name="HoTen" ColumnName="HoTen" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<EntitySetMapping Name="DanhSachLopHoc">
<EntityTypeMapping TypeName="IsTypeOf(Vidu.LopHoc)">
<MappingFragment StoreEntitySet="DanhSachLopHoc">
<ScalarProperty Name="MaLop" ColumnName="MaLop" />
<ScalarProperty Name="TenLop" ColumnName="TenLop" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<AssociationSetMapping Name="SinhVienLopHoc"
TypeName="Vidu.SinhVienLopHoc" StoreEntitySet="SinhVienLopHoc">
<EndProperty Name="SinhVien">
<ScalarProperty Name="MSSV" ColumnName="SinhVien_MSSV" />
</EndProperty>
<EndProperty Name="LopHoc">
<ScalarProperty Name="MaLop" ColumnName="LopHoc_MaLop" />
</EndProperty>
</AssociationSetMapping>
</EntityContainerMapping>
</Mapping></edmx:Mappings>
24
2.1.5
EDM (Entity Data Model): EDM bao gm ba phn chnh: m hnh nim
(Concept model), nh x (Mapping) v m hnh lu tr (Storage model).
o Concept model: m hnh nim l cc lp m hnh v cc mi quan h ca
n. iu ny s c c lp vi thit k bng c s d liu ca bn.
o Storage model: m hnh lu tr l m hnh thit k c s d liu bao gm
bng, view, th tc lu tr v cc mi quan h v cc kha ca n.
o Mapping: bn nh x bao gm thng tin v s nh x t m hnh nim
thnh m hnh lu tr.
ADO.Net Data Provider: l layer giao tip vi c s d liu theo tiu chun
ADO.Net.
DBDataReader c kt qu tr v t c s d liu.
lazy loading, ci thin kh nng kim tra, th h m ty bin v tin trnh Model
First.
-
Entity Framework 4.1: l phin bn u tin pht hnh NuGet. Phin bn ny bao
gm DbContext API v Code First c n gin ha.
Entity Framework 4.3: phin bn bao gm tnh nng mi Code First Migrations
(l qu trnh lm cho cc ng dng hin c c th chy trn cc my khc nhau hay
cc h iu hnh khc nhau) cho php mt c s d liu c to ra bi Code First
c thay i dn khi m hnh Code First ca bn pht trin.
Gii thiu
Cc tnh nng mi
Hiu
sut
truy
vn
ci
tin
http://blogs.msdn.com/b/adonet/archive/2012/02/14/sneak-preview-entityframework-5-0-performance-improvements.aspx
-
29
30
2.3.1.1 nh ngha
-
To Project ModelFirst
B2.
B3.
B4.
31
B5. Chn Empty Model v chn Finish. Vng thit k Entity Data Model
Designer hin ra
32
B6.
i tng Entity trn ToolBox vo vng thit k hay nhp phi vo vng
thit k chn Add New | Entity to ra cc i tng cn thit
Thm thuc tnh cho cc thc th, ta nhp phi chut vo thc th chn
Add New v chn cc loi thuc tnh mun thm. chnh sa cc thuc tnh
ta nhp chn vo thuc tnh chn Properties. Ca s Properties hin ra v
cha cc thng tin v thuc tnh ca thc th nh tn, kiu d liu ca thuc
tnh,.ta s thay i cc thng tin
33
B8.
34
B9.
35
B10.
x trong vng thit k. Nhp phi chut v chn Generate Database from
Model
B11. Ca s Generate Database Wizard xut hin:
36
37
B19. Click
Finish.
Bn
thy
cc
cu
lnh
trong
39
Lu bn ghi vo c s d liu:
db.HocVien.Add(h);
db.LopHoc.Add(l);
db.SaveChanges();
nh ngha
B2.
B4.
41
B5.
mun kt ni
B6.
ng dng:
42
B7.
B9.
To cc i tng mi:
43
nh ngha
Trong hng tip cn ny, ta hon ton lm vic vi code. Lp trnh vin s vit
cc ra cc lp m t cc i tng thc th tng ng vi cc bng trong c s
d liu. EF s t ng to ra c s d liu theo nhng g cc lp nh ngha.
44
2.3.3.2
-
To project mi
B1.
To project mi
B2.
t tn cho project
B3.
t tn Solution l CodeFirstEx
nh ngha cc lp khi to
B1.
B2.
B3.
B4.
Xa m lp Class1 c
B5.
// nh ngha hc vin
public class HocVien
{
public int HocVienId { get; set; }
public string HoTen { get; set; }
public bool GioiTinh { get; set; }
public DateTime NgaySinh { get; set; }
public DiaChi DiaChi { get; set; }
45
46
QuanLyHocVienContext
tha
lp
DbContext
trong
47
48
db.LopHocs.Add(l);
db.SaveChanges();
App.config:
<connectionStrings>
<add name="QuanLyHocVienDBConnectionString"
providerName="System.Data.SqlClient"
connectionString="Server=.\SQLEXPRESS;
Database=QuanLyHocVien2;
50
Trusted_Connection=True"/>
</connectionStrings>
51
//Database.SetInitializer<QuanLyHocVienDBContext>(new
DropCreateDatabaseIfModelChanges<QuanLyHocVienDBContext>());
//Database.SetInitializer<QuanLyHocVienDBContext>(new
DropCreateDatabaseAlways<QuanLyHocVienDBContext>());
//Database.SetInitializer<QuanLyHocVienDBContext>(new
QuanLyHocVienDBContextInitializer());
}
52
}
}
context.Database.Create();
}
}
Database.SetInitializer<QuanLyHocVienDBContext>(new
QuanLyHocVienDBContextInitializer());
2.3.3.5
DataAnnotation
-
thuc
tnh.
Bn
phi
khai
bo
khng
gian
tn
Annotation
Attribute
Required
MinLength
Quy nh di ti thiu ca k t
53
MaxLength
Quy nh di ti a ca k t
StringLength
Description
Table
Ch r tn bng m cc lp nh x
Column
Key
ComplexType
nh du cc lp nh loi phc hp
ForeignKey
nh du kha ngoi
NotMapped
V d:
[Table("DSHocVien")]
public class HocVien
{
[Key]
[Column("MaHocVien")]
public int HocVienId { get; set; }
[Required]
[StringLength(20)]
public string HoTen { get; set; }
[Required]
public bool GioiTinh { get; set; }
[Required]
public DateTime NgaySinh { get; set; }
[ForeignKey("LopHocId")]
public virtual ICollection<LopHoc> LopHocs { get; set; }
54
Fluent API
55
modelBuilder.Entity<HocVien>().Property(h =>
h.HocVienId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
HasMaxLength(): Thit lp s k t ti a:
modelBuilder.Entity<HocVien>().Property(h=>h.HoTen).HasMaxLength(50);
modelBuilder.ComplexType<DiaChi>().Property(d=>d.ThanhPho).HasMaxLength(20);
hoc:
modelBuilder.Entity<HocVien>().Property(h=>h.DiaChi.SoNha).HasMaxLength(20);
2.3.3.6
-
Cu hnh cc lin kt
Lin kt 1 1
56
S dng DataAnnotation:
public class Student
{
public Student() { }
[Required]
public virtual StudentAddress StudentAddress { get; set; }
}
base.OnModelCreating(modelBuilder);
57
Lin kt 1 nhiu
-
S dng DataAnnotation
58
{
StudentsList = new List<Student>();
}
public int StandardId { get; set; }
public string StandardName { get; set; }
public string Description { get; set; }
S dng DataAnnotation
59
2.3.3.7
-
Migration
Migration
mt
khi
to
cng
nh
CreateDatabaseIfNotExists,
DropCreateDatabaseIfModelChanges v DropCreateDatabaseAlways.
-
61
62
2.3.4
Loi c s
d liu
Loi tip
cn
M t
Khi bn cn to mt c s d liu mi
v mun thy thit k trn form giao
din, s dng model-first l thch hp
nht. Trong model-first:
C s d
liu mi
Tp trung vo
thit k
Model first
Khi bn c sn mt c s d liu v
mun thy thit k ca n trong form
giao din, bn s dng database-first:
C s d
liu tn
ti
Tp trung vo
thit k
Database
first
C s d
liu mi
Tp trung vo
code
Code first
63
Bn nh ngha cc lp cho mi
bng trong c s d liu bng
cch s dng code
nh ngha s nh x cho cc lp
bn nh ngha vi c s d liu
cn c gi l code-second do bn
Tp trung vo
code
Code first
Thm mt thc th
2.4.1.1
Thm mt thc th n
64
2.4.1.2
trong student */
student.StudentAddress = new StudentAddress() {
Address1 = "Student1's Address1",
Address2 = "Student1's Address2",
65
66
2.4.1.4
67
// To ra cc thc th Course
var course1 = new Course();
course1.CourseName = "New Course1";
course1.Location = "City1";
var course2 = new Course();
course2.CourseName = "New Course2";
course2.Location = "City2";
var course3 = new Course();
course3.CourseName = "New Course3";
course3.Location = "City1";
To DbContext v lu li:
using (var dbCtx = new SchoolDBEntities())
{
// Dng phng thc Add thm thc th DBSet
dbCtx.Students.Add(student1);
// Lu li thay i dng SaveChanges
dbCtx.SaveChanges();
}
2.4.2
Cp nht thc th
Ly ra thc th tn ti.
Student1").FirstOrDefault<Student>();
}
// Thay i tn Student
if (stud != null)
{
stud.StudentName = "Updated Student1";
}
// Lu li s thay i
using (var dbCtx = new SchoolDBEntities())
{
// nh du thc th b thay i bng State
dbCtx.Entry(stud).State = System.Data.EntityState.Modified;
dbCtx.SaveChanges();
}
-
Ngoi cch s dng trng thi ca thc th, ta c th khng cn gn cc trng thi
cho cc thc th m gi lun phng thc SaveChanges lu li nhng thay i.
Student stud ;
// Ly Student t c s d liu
using (var ctx = new SchoolDBEntities())
{
stud = ctx.Students.Where(s => s.StudentName == "New
Student1").FirstOrDefault<Student>();
if (stud != null)
{
69
// Thay i tn Student
stud.StudentName = "Updated Student1";
// Lu li s thay i
ctx.SaveChanges();
}
}
StudentAddress ca mt Student.
Xa thc th c lin kt. v d: Xa StudentAddress ca mt Student.
V d:
70
dbCtx.Entry<StudentAddress>(existingStudentAddress).State
= System.Data.EntityState.Deleted;
71
72
V d:
using (var dbCtx = new SchoolDBEntities())
{
/* 1- Ly d liu t c s d liu */
var existingStudent = dbCtx.Students.Include("Courses")
.Where(s => s.StudentName == stud.StudentName)
.FirstOrDefault<Student>();
/* 2- Tm danh sch kha hc s b xa bng cch ly danh
sch kha hc hin ti i danh sch kha hc tn ti*/
var deletedCourses =
existingStudent.Courses.Except(stud.Courses,
cours => cours.CourseId).ToList<Course>();
/* 3- Tm danh sch kha hc c thm vo bng cch ly
danh sch kha hc hin ti danh sch kha hc c sn */
var addedCourses =
stud.Courses.Except(existingStudent.Courses,
cours => cours.CourseId).ToList<Course>();
/* 4- Xa cc kha hc ra khi b tp kha hc ca sinh
vin
deletedCourses.ForEach(c =>
existingStudent.Courses.Remove(c));
//5- Thm kha hc mi
foreach(Course c in addedCourses)
{
/*6- Thm nhng kha hc mi vo tp cc kha hc nu
nh cha c*/
if (dbCtx.Entry(c).State ==
System.Data.EntityState.Detached)
dbCtx.Courses.Attach(c);
//7- Thm vo tp kha hc ca sinh vin
73
existingStudent.Courses.Add(c);
}
//8- Lu thay i
dbCtx.SaveChanges();
}
2.4.3
Xa thc th
Ly ra thc th cn xa.
74
2.5.2
-
C 3 cch to v s dng kiu Enum trong m hnh thc th d liu bng 3 cch:
Chuyn i mt thuc tnh c sn ca thc th thnh Enum t EDM
designer.
Thm Enum mi t EDM designer.
S dng kiu Enum t mt khng gian tn khc.
2.5.2.1
75
Sau khi chuyn thnh Enum, bn c th thy MonHocType trong Enum Type
trong Model Brower.
76
2.5.2.2
Click phi vo vng EDM Design chn Add New | Enum Type.
Nhp cc gi tr cho Enum nh phn trc trong hp thoi Add Enum Type.
Sau Enum ny s xut hin trong th mc Enum Types trong Model Browser.
77
2.5.2.3
-
Click phi vo vng EDM Design chn Add New | Enum Type.
2.5.3
-
MS SQL Server 2008 cung cp kiu d liu khng gian a l i din cho d liu
trong mt h ta v hnh hc vng quanh tri t m d liu i din nm trong
mt h ta Euclide (phng).
78
S dng:
ctx.Courses.Add(new Course() { CourseName = "New Course",
Location = DbGeography.FromText("POINT(-122.360 47.656)") });
ctx.SaveChanges();
2.5.4
-
Table-Valued Function
USE [QuanLyHocVien]
GO
/****** Object:
******/
UserDefinedFunction [dbo].[LayDSLopHocCuaHocVien]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[LayDSLopHocCuaHocVien]
(
-- Add the parameters for the function here
@HocVienId int
)
RETURNS TABLE
AS
79
RETURN
(
-- Add the SELECT statement with parameter references here
select c.Mon, c.GioHoc
from HocVien s left outer join HocVienLopHoc sc on
sc.HocVien_HocVienId = s.HocVienId join LopHoc c on
c.LopHocId=sc.LopHoc_LopHocId
where s.HocVienId = @HocVienId
)
Thm TVF bng cc click phi vo vng EDM Design ca m hnh v chn
Update Model from Database.
Trong hp thoi Update Wizard chn LayDSLopHocCuaHocVien ti Stored
Proceduces and Functions.
Chn Finish.
Bn s thy TVF LayDSLopHocCuaHocVien c hin th trong th mc
Function Imports v Stored Proceduces/Functions trong Model Browser.
Trong th mc Function Imports, click phi vo TVF va thm v chn Edit.
Chn kiu tr v ca TVF. Nu TVF ca bn tr v mt gi tr, chn Scalars
v chn kiu gi tr. Nu l mt tp hp cc record, chn Complex v t tn
80
S dng TVF:
81
2.5.5
-
Multiple diagrams
Visual Studio 2012 cho php bn phn chia m hnh d liu thc th thnh
nhiu s . Vic ny s gip bn d quan st cc s v mi quan h ca
82
Cc cch to ra cc s mi:
To mt s mi v ko th cc thc th t Model Browser vo.
Di chuyn mt thc th ti m hnh c vo m hnh mi.
2.5.6.1
To mt s mi v ko th cc thc th vo
Bn c th i tn cc s va to.
83
2.5.6.1
Di chuyn thc th t s c sn
2.5.7
85