CSharp: Add,Edit,Del,Select in donet using Entity Framework

 sql:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
--dbo.BillingDetails
--BillingDetailId int identity
--Owner
--Number
--BankName
--Swift
--CardType int
--ExpiryMonth
--ExpiryYear
--Discriminator
 
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].BillingDetails') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE BillingDetails
GO
create table BillingDetails
(
     BillingDetailId INT IDENTITY(1,1) PRIMARY KEY,
     [Owner] nvarchar(50) not  null,
     Number nvarchar(50)  null,
    --BankName nvarchar(50)  null,
    --Swift nvarchar(50)  null,
    --CardType int null,
    --ExpiryMonth nvarchar(50)  null,
    --ExpiryYear nvarchar(50)  null,
    Discriminator  nvarchar(50)  null
)
go
 
 
--BankAccount BankName  Swift
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].BankAccount') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE BankAccount
GO
create table BankAccount
(
     Id INT IDENTITY(1,1) PRIMARY KEY,
     BankName   nvarchar(50)  null,
     Swift nvarchar(50)  null
)
go
 
 
 
--CreditCard  CardType ExpiryMonth  ExpiryYear
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].CreditCard') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE CreditCard
GO
create table CreditCard
(
     Id INT IDENTITY(1,1) PRIMARY KEY,
     CardType  nvarchar(50)  null,
     ExpiryMonth  nvarchar(50)  null,
     ExpiryYear  nvarchar(50)  null
 
)
go
 
 
 
--dbo.Categories 
--CategoryId int
--CategoryName 50
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].Categories') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE Categories
GO
create table Categories
(
     CategoryId INT IDENTITY(1,1) PRIMARY KEY,
     CategoryName nvarchar(50) not null
)
go
 
 
 
--dbo.Products
--ProductId int identity
--ProductName 50
--CategoryId int  dbo.Categories CategoryId
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].Products') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE Products
GO
create table Products
(
    ProductId INT IDENTITY(1,1) PRIMARY KEY,
    ProductName nvarchar(50) not null,
    CategoryId int
        FOREIGN KEY REFERENCES Categories(CategoryId)
 
)
go
 
 
--dbo.Customers
--Id int identity
--Name 50
--Email  20
--CreatedTime date
--ModifiedTime date
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].Customers') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE Customers
GO
create table Customers
(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    [Name] nvarchar(50) not null,
    Email nvarchar(20) null,
    CreatedTime date null,
    ModifiedTime date null
)
go
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('geovindu','geovindu@163.com' ,getdate(),getdate())
go
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('test','geovindu@163.com' ,getdate(),getdate())
go
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('江城','geovindu@163.com' ,getdate(),getdate())
go
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('保中','geovindu@163.com' ,getdate(),getdate())
go
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('王二','geovindu@163.com' ,getdate(),getdate())
go
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('李三','geovindu@163.com' ,getdate(),getdate())
go
 
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('张四','geovindu@163.com' ,getdate(),getdate())
go
 
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('赵五','geovindu@163.com' ,getdate(),getdate())
go
 
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('陈六','geovindu@163.com' ,getdate(),getdate())
go
 
 
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('刘七','geovindu@163.com' ,getdate(),getdate())
go
 
 
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('徐八','geovindu@163.com' ,getdate(),getdate())
go
 
insert into Customers([Name],Email,CreatedTime,ModifiedTime) values('何九','geovindu@163.com' ,getdate(),getdate())
go
 
select * from Customers
go
 
 
 
--dbo.Orders
--Id int identity
--Quantity int
-- Code 400
--Price Decimal 18,4
--CustomerId int dbo.Customers CustomerId
--CreatedTime
--ModifiedTime
 
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].Orders') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE Orders
GO
create table Orders
(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    Quantity int null,
    Code nvarchar(400) null,
    Price decimal(18,4) null,
    CustomerId int
        FOREIGN KEY REFERENCES Customers(Id),
    CreatedTime date null,
    ModifiedTime date null
)
go
 
insert into Orders(Quantity,Code,Price,CustomerId,CreatedTime,ModifiedTime) values(10,N'4008',250.00,1,getdate(),getdate())
go
 
select * from Orders
go
 
 
 
--dbo.Students
--Id int identity
--Name
--Age byte
--CreatedTime date
-- ModifiedTime date
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].Students') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE Students
GO
create table Students
(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    [Name] nvarchar(50) not null,
    Age tinyint  null,
    CreatedTime date null,
    ModifiedTime date null
)
go
 
insert into Students([Name],Age,CreatedTime,ModifiedTime) values('sibodu',12,getdate(),getdate())
go
 
select * from Students
go
 
--StudentContact  ContactNumber
 
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].StudentContact') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE StudentContact
GO
create table StudentContact
(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    StudentId int
       FOREIGN KEY REFERENCES Students(Id),
    ContactNumber nvarchar(50) null
)
go
 
 
 
 
 
 
 
 
 
 
 
-- dbo.Courses
--Id  int identity
--Name
--MaximumStrength int
--CreatedTime
--ModifiedTime
--
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].Courses') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE Courses
GO
create table Courses
(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    [Name] nvarchar(50) not null,
    MaximumStrength int null,
    CreatedTime date null,
    ModifiedTime date null
)
go
 
insert into Courses([Name],MaximumStrength,CreatedTime,ModifiedTime) values('语文',25,getdate(),getdate())
go
 
 
select * from Courses
go
 
 
 
-- DropForeignKey("dbo.Orders", "CustomerId", "dbo.Customers");
-- DropForeignKey("dbo.Products", "CategoryId", "dbo.Categories");

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using DuEntity;
using DuInterface;
using DuUtilitieDB;
 
namespace DuDAL
{
 
    /// <summary>
    /// geovindu,Geovin Du 涂聚文 sql server
    /// EntityFramework 6.0
    /// </summary>
    public class CategoryDAL: ICategory
    {
 
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public int Add(Category category)
        {
            int addok = 0;
 
            try
            {
                using (var context = new DuDbContext())
                {
                    //context.Database.ExecuteSqlCommand("");
                    context.Categories.Add(category);
                    addok = context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            return addok;
        }
 
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public int Update(Category category)
        {
            int edidok = 0;
            try
            {
                using (var context = new DuDbContext())
                {
                    // edidok = ctx.Database.ExecuteSqlCommand("");                
                    context.Entry(category).State = category.CategoryId == 0 ? EntityState.Added : EntityState.Modified;
                    edidok = context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
 
            return edidok;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public int Delte(int categoryId)
        {
            int delok = 0;
            try
            {
                using (var context = new DuDbContext())
                {
                    // delok = ctx.Database.ExecuteSqlCommand("");                  
                   var dellist=context.Categories.Where(c => c.CategoryId == categoryId).ToList();
                    if(dellist.Count > 0)
                    {
                        context.Categories.RemoveRange(dellist);
                        delok = context.SaveChanges();
                        // context.Categories.Where(x => x.CategoryId == categoryId).DefaultIfEmpty();
                        //context.Categories.Where(x => x.CategoryId == categoryId).DeleteFromQuery();
 
                    }
 
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
 
            return delok;
        }
        /// <summary>
        /// 查找一个实例
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public Category SelectInfo(int categoryId)
        {          
 
            Category category= null;   
            try
            {
                using (var context = new DuDbContext())
                {
                    // delok = ctx.Database.ExecuteSqlCommand("");                  
                    //category = context.Categories.Where(c => c.CategoryId == categoryId);            
                    category = context.Categories.FindAsync(categoryId).Result;
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
 
            return category;
        }
 
    }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using (var ctx = new EfDbContext())
            {
                ctx.Database.Log = Console.WriteLine;
 
                // var customers = ctx.Customers;
 
                //var customer = customers.FirstOrDefault(d => d.Id == 1); // customers.FindAsync(1).Result;
                //Console.WriteLine(customer.Name);
 
                //bool contains = customers.Where(c => c.Name == "geovindu").Contains(customer);
 
 
                //添加
                //var addcustomer = new Customer()
                //{
                //    Name = "涂聚文",
                //    Email = "463588883@qq.com",
                //    CreatedTime = DateTime.Now,
                //    ModifiedTime = DateTime.Now
                //};
                //ctx.Customers.Add(addcustomer);
                //int k=ctx.SaveChanges();
 
 
                //修改
                // var editcustomer = new Customer()
                // {
                //   Id =1,
                //   Name="涂年生",
                //   Email="463588883@qq.com",
                //   CreatedTime=DateTime.Now,
                //   ModifiedTime=DateTime.Now
 
                // };
                // ctx.Entry(editcustomer).State=System.Data.Entity.EntityState.Modified;
                //int k=ctx.SaveChanges();
                // if (k > 0)
                //     Console.WriteLine("ok,eidt");
 
                //删除
                //var delcustomer = new Customer()
                //{
                //    Id= 3
                //};
 
                //ctx.Entry(delcustomer).State = System.Data.Entity.EntityState.Deleted;
                //int k = ctx.SaveChanges();
                //if (k > 0)
                //    Console.WriteLine("ok del");
 
 
                //查询集合
                var customers = ctx.Customers;
 
                //var names = customers
                //    .Select(x => x.Name)
                //    //.Take(10)
                //    .OrderBy(d=>1)
                //    .Skip(5)                   
                //    .ToList();
 
                var names = customers
                    .Select(x => x.Name)
                    .Take(10)
                    .OrderBy(d => 1)
                    //.Skip(5)
                    .ToList();
 
                foreach (var name in names)
                {
                    Console.WriteLine(name+"\n\t");
                }
 
                //原始查询
                var cus = ctx.Database.SqlQuery<Customer>("SELECT * FROM dbo.Customers").ToList();
 
                foreach (var cs in cus)
                {
                    Console.WriteLine("name:"+cs.Name + "\n\t");
                }
 
                var id = 1;
                var par = new SqlParameter[]
                    {
                        new SqlParameter(){ ParameterName="@id",SqlDbType=SqlDbType.Int,Value=id },
                    };
                var cust = ctx.Database.SqlQuery<Customer>("SELECT * FROM dbo.Customers where id=@id", par).ToList();
 
 
 
 
            }
            Console.ReadKey();

 实体添加,修改,删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//添加
var addcustomer = new Customer()
{
    Name = "涂聚文",
    Email = "463588883@qq.com",
    CreatedTime = DateTime.Now,
    ModifiedTime = DateTime.Now
};
ctx.Customers.Add(addcustomer);
ctx.Entry(addcustomer).State = System.Data.Entity.EntityState.Added;
int k = ctx.SaveChanges();
 
 
//修改
 var editcustomer = new Customer()
 {
     Id = 1,
     Name = "涂年生",
     Email = "463588883@qq.com",
     CreatedTime = DateTime.Now,
     ModifiedTime = DateTime.Now
 
 };
ctx.Entry(editcustomer).State = System.Data.Entity.EntityState.Modified;
 k = ctx.SaveChanges();
if (k > 0)
    Console.WriteLine("ok,eidt");
 
//删除
var delcustomer = new Customer()
{
    Id = 14
};
 
ctx.Entry(delcustomer).State = System.Data.Entity.EntityState.Deleted;
 k = ctx.SaveChanges();
if (k > 0)
    Console.WriteLine("ok del");

  

 

开发环境(Development)
演示(模拟、临时)环境(Staging)
生产环境(Production)
测试环境(Testing)
预发布环境(UAT)
正式环境(Production)

data structures and algorithms
https://github.com/PacktPublishing/C-Sharp-Data-Structures-and-Algorithms
https://github.com/aalhour/C-Sharp-Algorithms
https://github.com/abdonkov/DSA
https://github.com/scottfalbo/data-structures-and-algorithms
https://github.com/anirban-s/data-structures-and-algorithms
https://github.com/akgmage/data-structures-and-algorithms
Collection of well known Data Structures, and Algorithms in Go, C++, Java & Python
https://github.com/phishman3579/java-algorithms-implementation
https://github.com/thepranaygupta/Data-Structures-and-Algorithms
https://kentdlee.github.io/CS2Plus/build/html/index.html
https://github.com/kentdlee/CS2Plus
https://github.com/YanxinHuang/data-structure-and-algorithm
https://www.codeproject.com/articles/16337/back-to-basics-generic-data-structures-and-algorit
https://github.com/krahets/hello-algo
《Hello 算法》一本动画图解、能运行、可提问的数据结构与算法入门书。提供 Java, C++, Python, Go, JS, TS, C# 源代码。
https://github.com/topics/data-structures-and-algorithms

  

posted @   ®Geovin Du Dream Park™  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2022-01-26 CSharp: itext7.* create pdf file
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示