using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleEFApplication2 { class Program { static void Main(string[] args) { StudyDBEntities context = new StudyDBEntities(); /* // 增 Student s1 = new Student(); s1.Name = "张三"; s1.Class = "101班"; context.Student.Add(s1); context.SaveChanges(); */ /* 跟踪数据库操作为: INSERT [Student]([Name], [Class]) VALUES (‘李四‘,‘103班‘) SELECT [ID] FROM [Student] WHERE @@ROWCOUNT > 0 AND [ID] = scope_identity() */ /* // 删 int id = 1; var s3 = from s in context.Student where s.ID == id select s; context.Student.Remove(s3.FirstOrDefault()); context.SaveChanges(); */ /* SELECT TOP (1) [Extent1].[ID] AS [ID], [Extent1].[Name] AS [Name], [Extent1].[Class] AS [Class] FROM [dbo].[Student] AS [Extent1] WHERE [Extent1].[ID] = 1 DELETE [dbo].[Student] WHERE ([ID] = 1) */ // 改 int id = 2; var s3 = from s in context.Student where s.ID == id select s; var m = s3.FirstOrDefault(); m.Name = "王五"; context.SaveChanges(); /* SELECT TOP (1) [Extent1].[ID] AS [ID], [Extent1].[Name] AS [Name], [Extent1].[Class] AS [Class] FROM [dbo].[Student] AS [Extent1] WHERE [Extent1].[ID] = 2 UPDATE [dbo].[Student] SET [Name] = ‘王五‘ WHERE ([ID] = 2) */ // 查 // 1. 两者等同 var s1 = context.Student.Select(s => s); foreach (var item in s1) { Console.WriteLine(item.ID); } /* 跟踪数据库操作为: SELECT [Extent1].[ID] AS [ID], [Extent1].[Name] AS [Name], [Extent1].[Class] AS [Class] FROM [dbo].[Student] AS [Extent1] */ var s2 = from s in context.Student where s.ID > 1 && s.Name.StartsWith("李") select s.Name; // s2 = context.Student.Select(s => s.Name); foreach (var item in s2) { Console.WriteLine(item); } /* 跟踪数据库操作为: SELECT [Extent1].[Name] AS [Name] FROM [dbo].[Student] AS [Extent1] WHERE ([Extent1].[ID] > 1) AND ([Extent1].[Name] LIKE ‘李%‘) */ } } }
原文:http://www.cnblogs.com/z5337/p/5245829.html