新建个表,我用的是sql server2014,我会把文件发上来,如果是低版本的,可以执行语句,数据库就自己创建吧。
USE [testdb] GO CREATE TABLE [dbo].[Product]( [ID] [int] IDENTITY(1,1) NOT NULL, [ProductId] [nvarchar](50) NULL, [ProductCode] [nvarchar](50) NULL, [ProductName] [nvarchar](255) NULL, [MarkPrice] [decimal](18, 2) NULL, [TruePrice] [decimal](18, 2) NULL, [Discount] [nvarchar](10) NULL, [IsWebPub] [int] NULL, [CityId] [int] NULL, [CityName] [nvarchar](50) NULL, [Sort] [decimal](18, 0) NULL, [Createtime] [datetime] NULL, [IsDelete] [int] NULL, CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
我创建了一个控制台应用程序,就不截图了
创建一个数据实体模型,也就是EDMX
数据库连接字符串,在App.config中
<connectionStrings>
<add name="mytestdbEntities" connectionString="metadata=res://*/testdb.csdl|res://*/testdb.ssdl|res://*/testdb.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=testdb;persist security info=True;user id=sa;password=123456;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
来吧,写个增删改查:
//增加 Product p1 = new Product() { CityId = 1, CityName = "北京", Createtime = DateTime.Now, Discount = "22", IsWebPub = 1, ProductId = "3", ProductCode = "0001", MarkPrice = 50, ProductName = "苹果", Sort = 1, TruePrice = 20 }; Product p2 = new Product() { CityId = 2, CityName = "上海", Createtime = DateTime.Now, Discount = "22", IsWebPub = 1, ProductId = "2", ProductCode = "0002", MarkPrice = 6, ProductName = "大Y梨", Sort = 1, TruePrice = 5 }; using (mytestdbEntities dbefadd = new mytestdbEntities()) { dbefadd.Product.Add(p1); dbefadd.Product.Add(p2); int retnum = dbefadd.SaveChanges(); Console.WriteLine("add_{0}_ok", retnum); } //add_2_ok
//删除 using (mytestdbEntities dbefdel = new mytestdbEntities()) { //删除一条 // dbefdel.Product.Remove(p1); // dbefdel.SaveChanges(); var entitys = dbefdel.Product.Where(p => p.ProductId == "1"); //删除多条 dbefdel.Product.RemoveRange(entitys); int retnum = dbefdel.SaveChanges(); Console.WriteLine("del_{0}_ok", retnum); }
//修改 using (mytestdbEntities dbefedit = new mytestdbEntities()) { var p = dbefedit.Product.FirstOrDefault(); p.ProductName = "就把你名字改了"; int retnum = dbefedit.SaveChanges(); Console.WriteLine("edit_{0}_ok", retnum); }
//查询 using (mytestdbEntities dbefsel = new mytestdbEntities()) { //查询一条 var p = dbefsel.Product.FirstOrDefault(); Console.WriteLine("查询一条:{0}|{1}|{2}|{3}", p.ProductId, p.ProductName, p.ProductCode, p.TruePrice); //查询一个集合 var list = dbefsel.Product.Where(pp => pp.ProductId == "2"); foreach (var item in list) { Console.WriteLine("查询多条:{0}|{1}|{2}|{3}", item.ProductId, item.ProductName, item.ProductCode, item.TruePrice); } Console.WriteLine("sel_ok"); } Console.ReadLine();