-
Notifications
You must be signed in to change notification settings - Fork 62
/
NorthwindIBModelController.cs
1088 lines (950 loc) · 39 KB
/
NorthwindIBModelController.cs
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Only one of the next few should be uncommented.
#define CODEFIRST_PROVIDER
// #define NHIBERNATE
// OLD defines
//#define DATABASEFIRST_NEW
//#define ORACLE_EDMX
using System;
using System.Net;
using System.Linq;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Web.Http;
using Breeze.ContextProvider;
using Breeze.WebApi2;
using Microsoft.SqlServer.Server;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using NHibernate.Mapping;
using NHibernate.Transform;
using System.Threading.Tasks;
#if CODEFIRST_PROVIDER
using Breeze.ContextProvider.EF6;
using Models.NorthwindIB.CF;
using Foo;
using System.ComponentModel.DataAnnotations;
using System.Web.Http.OData.Query;
#elif DATABASEFIRST_OLD
using Breeze.ContextProvider.EF6;
using Models.NorthwindIB.EDMX;
#elif DATABASEFIRST_NEW
using Breeze.ContextProvider.EF6;
using Models.NorthwindIB.EDMX_2012;
#elif ORACLE_EDMX
using Breeze.ContextProvider.EF6;
using Models.NorthwindIB.Oracle;
#elif NHIBERNATE
using Breeze.ContextProvider.NH;
using NHibernate;
using NHibernate.Linq;
using Models.NorthwindIB.NH;
#endif
namespace Sample_WebApi2.Controllers {
#if NHIBERNATE
[BreezeNHController]
#else
[BreezeController]
#endif
public class NorthwindIBModelController : ApiController {
private NorthwindContextProvider ContextProvider;
public NorthwindIBModelController() {
ContextProvider = new NorthwindContextProvider();
}
//[HttpGet]
//public String Metadata() {
// var folder = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data");
// var fileName = Path.Combine(folder, "metadata.json");
// var jsonMetadata = File.ReadAllText(fileName);
// return jsonMetadata;
//}
//[HttpGet]
//public HttpResponseMessage Metadata() {
// var result = new HttpResponseMessage { Content = new StringContent(ContextProvider.Metadata())};
// result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// return result;
//}
[HttpGet]
public String Metadata() {
return ContextProvider.Metadata();
}
//[HttpPost]
//public SaveResult SaveChanges(JObject saveBundle) {
// return ContextProvider.SaveChanges(saveBundle);
//}
[HttpPost]
public Task<SaveResult> SaveChanges(JObject saveBundle) {
return ContextProvider.SaveChangesAsync(saveBundle);
}
#region Save interceptors
[HttpPost]
public SaveResult SaveWithTransactionScope(JObject saveBundle) {
var txSettings = new TransactionSettings() { TransactionType = TransactionType.TransactionScope };
return ContextProvider.SaveChanges(saveBundle, txSettings);
}
[HttpPost]
public SaveResult SaveWithDbTransaction(JObject saveBundle) {
var txSettings = new TransactionSettings() { TransactionType = TransactionType.DbTransaction };
return ContextProvider.SaveChanges(saveBundle, txSettings);
}
[HttpPost]
public SaveResult SaveWithNoTransaction(JObject saveBundle) {
var txSettings = new TransactionSettings() { TransactionType = TransactionType.None };
return ContextProvider.SaveChanges(saveBundle, txSettings);
}
[HttpPost]
public Task<SaveResult> SaveWithComment(JObject saveBundle) {
ContextProvider.BeforeSaveEntitiesDelegate = AddComment;
return ContextProvider.SaveChangesAsync(saveBundle);
}
[HttpPost]
public SaveResult SaveWithExit(JObject saveBundle) {
// set break points here to see how these two approaches give you a SaveMap w/o saving.
var saveMap = ContextProvider.GetSaveMapFromSaveBundle(saveBundle);
saveMap = new NorthwindIBDoNotSaveContext().GetSaveMapFromSaveBundle(saveBundle);
return new SaveResult() { Entities = new List<Object>(), KeyMappings = new List<KeyMapping>() };
}
[HttpPost]
public Task<SaveResult> SaveAndThrow(JObject saveBundle) {
ContextProvider.BeforeSaveEntitiesDelegate = ThrowError;
return ContextProvider.SaveChangesAsync(saveBundle);
}
[HttpPost]
public Task<SaveResult> SaveWithEntityErrorsException(JObject saveBundle) {
ContextProvider.BeforeSaveEntitiesDelegate = ThrowEntityErrorsException;
return ContextProvider.SaveChangesAsync(saveBundle);
}
[HttpPost]
public Task<SaveResult> SaveWithAuditFields(JObject saveBundle) {
ContextProvider.BeforeSaveEntityDelegate = SetAuditFields;
return ContextProvider.SaveChangesAsync(saveBundle);
}
[HttpPost]
public Task<SaveResult> SaveWithFreight(JObject saveBundle) {
ContextProvider.BeforeSaveEntityDelegate = CheckFreight;
return ContextProvider.SaveChangesAsync(saveBundle);
}
[HttpPost]
public Task<SaveResult> SaveWithFreight2(JObject saveBundle) {
ContextProvider.BeforeSaveEntitiesDelegate = CheckFreightOnOrders;
return ContextProvider.SaveChangesAsync(saveBundle);
}
[HttpPost]
public Task<SaveResult> SaveCheckInitializer(JObject saveBundle) {
ContextProvider.BeforeSaveEntitiesDelegate = AddOrder;
return ContextProvider.SaveChangesAsync(saveBundle);
}
[HttpPost]
public Task<SaveResult> SaveCheckUnmappedProperty(JObject saveBundle) {
ContextProvider.BeforeSaveEntityDelegate = CheckUnmappedProperty;
return ContextProvider.SaveChangesAsync(saveBundle);
}
[HttpPost]
public Task<SaveResult> SaveCheckUnmappedPropertySerialized(JObject saveBundle) {
ContextProvider.BeforeSaveEntityDelegate = CheckUnmappedPropertySerialized;
return ContextProvider.SaveChangesAsync(saveBundle);
}
[HttpPost]
public Task<SaveResult> SaveCheckUnmappedPropertySuppressed(JObject saveBundle) {
ContextProvider.BeforeSaveEntityDelegate = CheckUnmappedPropertySuppressed;
return ContextProvider.SaveChangesAsync(saveBundle);
}
private Dictionary<Type, List<EntityInfo>> ThrowError(Dictionary<Type, List<EntityInfo>> saveMap) {
throw new Exception("Deliberately thrown exception");
}
private Dictionary<Type, List<EntityInfo>> ThrowEntityErrorsException(Dictionary<Type, List<EntityInfo>> saveMap) {
List<EntityInfo> orderInfos;
if (saveMap.TryGetValue(typeof(Order), out orderInfos)) {
var errors = orderInfos.Select(oi => {
#if NHIBERNATE
return new EntityError() {
EntityTypeName = typeof(Order).FullName,
ErrorMessage = "Cannot save orders with this save method",
ErrorName = "WrongMethod",
KeyValues = new object[] { ((Order) oi.Entity).OrderID },
PropertyName = "OrderID"
};
#else
return new EFEntityError(oi, "WrongMethod", "Cannot save orders with this save method", "OrderID");
#endif
});
var ex = new EntityErrorsException("test of custom exception message", errors);
// if you want to see a different error status code use this.
// ex.StatusCode = HttpStatusCode.Conflict; // Conflict = 409 ; default is Forbidden (403).
throw ex;
}
return saveMap;
}
private Dictionary<Type, List<EntityInfo>> AddOrder(Dictionary<Type, List<EntityInfo>> saveMap) {
var order = new Order();
order.OrderDate = DateTime.Today;
var ei = ContextProvider.CreateEntityInfo(order);
List<EntityInfo> orderInfos = ContextProvider.GetEntityInfos(saveMap, typeof(Order));
orderInfos.Add(ei);
return saveMap;
}
private Dictionary<Type, List<EntityInfo>> CheckFreightOnOrders(Dictionary<Type, List<EntityInfo>> saveMap) {
List<EntityInfo> entityInfos;
if (saveMap.TryGetValue(typeof(Order), out entityInfos)) {
foreach (var entityInfo in entityInfos) {
CheckFreight(entityInfo);
}
}
return saveMap;
}
private bool CheckFreight(EntityInfo entityInfo) {
if ((ContextProvider.SaveOptions.Tag as String) == "freight update") {
var order = entityInfo.Entity as Order;
order.Freight = order.Freight + 1;
} else if ((ContextProvider.SaveOptions.Tag as String) == "freight update-ov") {
var order = entityInfo.Entity as Order;
order.Freight = order.Freight + 1;
entityInfo.OriginalValuesMap["Freight"] = null;
} else if ((ContextProvider.SaveOptions.Tag as String) == "freight update-force") {
var order = entityInfo.Entity as Order;
order.Freight = order.Freight + 1;
entityInfo.ForceUpdate = true;
}
return true;
}
private bool SetAuditFields(EntityInfo entityInfo) {
var entity = entityInfo.Entity as User;
if (entity == null) return true;
var userId = 12345;
if (entityInfo.EntityState == Breeze.ContextProvider.EntityState.Added)
{
entityInfo.OriginalValuesMap["CreatedBy"] = entity.CreatedBy;
entityInfo.OriginalValuesMap["CreatedByUserId"] = entity.CreatedByUserId;
entityInfo.OriginalValuesMap["CreatedDate"] = entity.CreatedDate;
//entityInfo.ForceUpdate = true;
entity.CreatedBy = "test";
entity.CreatedByUserId = userId;
entity.CreatedDate = DateTime.Now;
entity.ModifiedBy = "test";
entity.ModifiedByUserId = userId;
entity.ModifiedDate = DateTime.Now;
} else if (entityInfo.EntityState == Breeze.ContextProvider.EntityState.Modified)
{
entityInfo.OriginalValuesMap["ModifiedBy"] = entity.ModifiedBy;
entityInfo.OriginalValuesMap["ModifiedByUserId"] = entity.ModifiedByUserId;
entityInfo.OriginalValuesMap["ModifiedDate"] = entity.ModifiedDate;
//entityInfo.ForceUpdate = true;
entity.ModifiedBy = "test";
entity.ModifiedByUserId = userId;
entity.ModifiedDate = DateTime.Now;
}
return true;
}
private Dictionary<Type, List<EntityInfo>> AddComment(Dictionary<Type, List<EntityInfo>> saveMap) {
var comment = new Comment();
var tag = ContextProvider.SaveOptions.Tag;
comment.Comment1 = (tag == null) ? "Generic comment" : tag.ToString();
comment.CreatedOn = DateTime.Now;
comment.SeqNum = 1;
var ei = ContextProvider.CreateEntityInfo(comment);
List<EntityInfo> commentInfos = ContextProvider.GetEntityInfos(saveMap, typeof(Comment));
commentInfos.Add(ei);
return saveMap;
}
private bool CheckUnmappedProperty(EntityInfo entityInfo) {
var unmappedValue = entityInfo.UnmappedValuesMap["MyUnmappedProperty"];
// fixed in v 1.4.18
// var unmappedValue = entityInfo.UnmappedValuesMap["myUnmappedProperty"];
if ((String)unmappedValue != "anything22") {
throw new Exception("wrong value for unmapped property: " + unmappedValue);
}
Customer cust = entityInfo.Entity as Customer;
return false;
}
private bool CheckUnmappedPropertySuppressed(EntityInfo entityInfo) {
if (entityInfo.UnmappedValuesMap != null) {
throw new Exception("unmapped properties should have been suppressed");
}
return false;
}
private bool CheckUnmappedPropertySerialized(EntityInfo entityInfo) {
var unmappedValue = entityInfo.UnmappedValuesMap["MyUnmappedProperty"];
if ((String)unmappedValue != "ANYTHING22") {
throw new Exception("wrong value for unmapped property: " + unmappedValue);
}
var anotherOne = entityInfo.UnmappedValuesMap["AnotherOne"];
if (((dynamic) anotherOne).z[5].foo.Value != 4) {
throw new Exception("wrong value for 'anotherOne.z[5].foo'");
}
if (((dynamic)anotherOne).extra.Value != 666) {
throw new Exception("wrong value for 'anotherOne.extra'");
}
Customer cust = entityInfo.Entity as Customer;
if (cust.CompanyName.ToUpper() != cust.CompanyName) {
throw new Exception("Uppercasing of company name did not occur");
}
return false;
}
#endregion
#region standard queries
[HttpGet]
#if NHIBERNATE
[BreezeNHQueryable(MaxAnyAllExpressionDepth = 3)]
#else
[EnableBreezeQuery(MaxAnyAllExpressionDepth = 3)]
#endif
public IQueryable<Customer> Customers() {
return ContextProvider.Context.Customers;
}
[HttpGet]
#if NHIBERNATE
[BreezeNHQueryable(MaxExpansionDepth = 3)]
#else
[EnableBreezeQuery(MaxExpansionDepth = 3)]
#endif
public IQueryable<Order> Orders() {
return ContextProvider.Context.Orders;
}
[HttpGet]
public IQueryable<Employee> Employees() {
return ContextProvider.Context.Employees;
}
[HttpGet]
public IQueryable<OrderDetail> OrderDetails() {
return ContextProvider.Context.OrderDetails;
}
[HttpGet]
public IQueryable<Product> Products() {
return ContextProvider.Context.Products;
}
[HttpGet]
public IQueryable<Supplier> Suppliers() {
return ContextProvider.Context.Suppliers;
}
[HttpGet]
public IQueryable<Region> Regions() {
return ContextProvider.Context.Regions;
}
[HttpGet]
public IQueryable<Territory> Territories() {
return ContextProvider.Context.Territories;
}
[HttpGet]
public IQueryable<Category> Categories() {
return ContextProvider.Context.Categories;
}
[HttpGet]
public IQueryable<Role> Roles() {
return ContextProvider.Context.Roles;
}
[HttpGet]
public IQueryable<User> Users() {
return ContextProvider.Context.Users;
}
[HttpGet]
public IQueryable<TimeLimit> TimeLimits() {
return ContextProvider.Context.TimeLimits;
}
[HttpGet]
public IQueryable<TimeGroup> TimeGroups() {
return ContextProvider.Context.TimeGroups;
}
[HttpGet]
public IQueryable<Comment> Comments() {
return ContextProvider.Context.Comments;
}
[HttpGet]
public IQueryable<UnusualDate> UnusualDates() {
return ContextProvider.Context.UnusualDates;
}
#if ! DATABASEFIRST_OLD
[HttpGet]
public IQueryable<Geospatial> Geospatials() {
return ContextProvider.Context.Geospatials;
}
#endif
#endregion
#region named queries
[HttpGet]
public IQueryable<Customer> CustomersStartingWith(string companyName) {
if (companyName == "null") {
throw new Exception("nulls should not be passed as 'null'");
}
if (String.IsNullOrEmpty(companyName)) {
companyName = "";
}
var custs = ContextProvider.Context.Customers.Where(c => c.CompanyName.StartsWith(companyName));
return custs;
}
[HttpGet]
public Object CustomerCountsByCountry() {
return ContextProvider.Context.Customers.GroupBy(c => c.Country).Select(g => new { g.Key, Count = g.Count() });
}
[HttpGet]
public Customer CustomerWithScalarResult() {
return ContextProvider.Context.Customers.First();
}
[HttpGet]
public IQueryable<Customer> CustomersWithHttpError() {
var responseMsg = new HttpResponseMessage(HttpStatusCode.NotFound);
responseMsg.Content = new StringContent("Custom error message");
responseMsg.ReasonPhrase = "Custom Reason";
throw new HttpResponseException(responseMsg);
}
[HttpGet]
[EnableBreezeQuery]
public IEnumerable<Employee> EnumerableEmployees() {
return ContextProvider.Context.Employees.ToList();
}
[HttpGet]
public IQueryable<Employee> EmployeesFilteredByCountryAndBirthdate(DateTime birthDate, string country) {
return ContextProvider.Context.Employees.Where(emp => emp.BirthDate >= birthDate && emp.Country == country);
}
[HttpGet]
public List<Employee> QueryInvolvingMultipleEntities() {
#if NHIBERNATE
// need to figure out what to do here
//return new List<Employee>();
var dc0 = new NorthwindNHContext();
var dc = new NorthwindNHContext();
#elif CODEFIRST_PROVIDER
var dc0 = new NorthwindIBContext_CF();
var dc = new EFContextProvider<NorthwindIBContext_CF>();
#elif DATABASEFIRST_OLD
var dc0 = new NorthwindIBContext_EDMX();
var dc = new EFContextProvider<NorthwindIBContext_EDMX>();
#elif DATABASEFIRST_NEW
var dc0 = new NorthwindIBContext_EDMX_2012();
var dc = new EFContextProvider<NorthwindIBContext_EDMX_2012>();
#elif ORACLE_EDMX
var dc0 = new NorthwindIBContext_EDMX_Oracle();
var dc = new EFContextProvider<NorthwindIBContext_EDMX_Oracle>();
#endif
//the query executes using pure EF
var query0 = (from t1 in dc0.Employees
where (from t2 in dc0.Orders select t2.EmployeeID).Distinct().Contains(t1.EmployeeID)
select t1);
var result0 = query0.ToList();
//the same query fails if using EFContextProvider
dc0 = dc.Context;
var query = (from t1 in dc0.Employees
where (from t2 in dc0.Orders select t2.EmployeeID).Distinct().Contains(t1.EmployeeID)
select t1);
var result = query.ToList();
return result;
}
[HttpGet]
public Customer CustomerFirstOrDefault() {
var customer = ContextProvider.Context.Customers.Where(c => c.CompanyName.StartsWith("blah")).FirstOrDefault();
return customer;
}
[HttpGet]
public Int32 OrdersCountForCustomer(string companyName) {
var customer =
ContextProvider.Context.Customers.Include("Orders").Where(c => c.CompanyName.StartsWith(companyName)).First();
return customer.Orders.Count;
}
[HttpGet]
// AltCustomers will not be in the resourceName/entityType map;
public IQueryable<Customer> AltCustomers() {
return ContextProvider.Context.Customers;
}
[HttpGet]
public IQueryable<Employee> SearchEmployees([FromUri] int[] employeeIds) {
var query = ContextProvider.Context.Employees.AsQueryable();
if (employeeIds.Length > 0) {
query = query.Where(emp => employeeIds.Contains(emp.EmployeeID));
var result = query.ToList();
}
return query;
}
[HttpGet]
public IQueryable<Customer> SearchCustomers([FromUri] CustomerQBE qbe) {
// var query = ContextProvider.Context.Customers.Where(c =>
// c.CompanyName.StartsWith(qbe.CompanyName));
var ok = qbe != null && qbe.CompanyName != null & qbe.ContactNames.Length > 0 && qbe.City.Length > 1;
if (!ok) {
throw new Exception("qbe error");
}
// just testing that qbe actually made it in not attempted to write qbe logic here
// so just return first 3 customers.
return ContextProvider.Context.Customers.Take(3);
}
[HttpGet]
public IQueryable<Customer> SearchCustomers2([FromUri] CustomerQBE[] qbeList) {
if (qbeList.Length < 2) {
throw new Exception("all least two items must be passed in");
}
var ok = qbeList.All(qbe => {
return qbe.CompanyName != null & qbe.ContactNames.Length > 0 && qbe.City.Length > 1;
});
if (!ok) {
throw new Exception("qbeList error");
}
// just testing that qbe actually made it in not attempted to write qbe logic here
// so just return first 3 customers.
return ContextProvider.Context.Customers.Take(3);
}
public class CustomerQBE {
public String CompanyName { get; set; }
public String[] ContactNames { get; set; }
public String City { get; set; }
}
[HttpGet]
public IQueryable<Customer> CustomersOrderedStartingWith(string companyName) {
var customers = ContextProvider.Context.Customers.Where(c => c.CompanyName.StartsWith(companyName)).OrderBy(cust => cust.CompanyName);
var list = customers.ToList();
return customers;
}
[HttpGet]
public IQueryable<Employee> EmployeesMultipleParams(int employeeID, string city) {
// HACK:
if (city == "null") {
city = null;
}
var emps = ContextProvider.Context.Employees.Where(emp => emp.EmployeeID == employeeID || emp.City.Equals(city));
return emps;
}
[HttpGet]
public IEnumerable<Object> Lookup1Array() {
var regions = ContextProvider.Context.Regions;
var lookups = new List<Object>();
lookups.Add(new {regions = regions});
return lookups;
}
[HttpGet]
public object Lookups() {
var regions = ContextProvider.Context.Regions;
var territories = ContextProvider.Context.Territories;
var categories = ContextProvider.Context.Categories;
var lookups = new { regions, territories, categories };
return lookups;
}
[HttpGet]
public IEnumerable<Object> LookupsEnumerableAnon() {
var regions = ContextProvider.Context.Regions;
var territories = ContextProvider.Context.Territories;
var categories = ContextProvider.Context.Categories;
var lookups = new List<Object>();
lookups.Add(new {regions = regions, territories = territories, categories = categories});
return lookups;
}
[HttpGet]
public IQueryable<Object> CompanyNames() {
var stuff = ContextProvider.Context.Customers.Select(c => c.CompanyName);
return stuff;
}
[HttpGet]
public IQueryable<Object> CompanyNamesAndIds() {
var stuff = ContextProvider.Context.Customers.Select(c => new { c.CompanyName, c.CustomerID });
return stuff;
}
[HttpGet]
public IQueryable<CustomerDTO> CompanyNamesAndIdsAsDTO() {
var stuff = ContextProvider.Context.Customers.Select(c => new CustomerDTO() { CompanyName = c.CompanyName, CustomerID = c.CustomerID });
return stuff;
}
public class CustomerDTO {
public CustomerDTO() {
}
public CustomerDTO(String companyName, Guid customerID) {
CompanyName = companyName;
CustomerID = customerID;
}
public Guid CustomerID { get; set; }
public String CompanyName { get; set; }
public AnotherType AnotherItem { get; set; }
}
public class AnotherType {
}
[HttpGet]
public IQueryable<Object> CustomersWithBigOrders() {
var stuff = ContextProvider.Context.Customers.Where(c => c.Orders.Any(o => o.Freight > 100)).Select(c => new { Customer = c, BigOrders = c.Orders.Where(o => o.Freight > 100) });
return stuff;
}
[HttpGet]
#if NHIBERNATE
public IQueryable<Object> CompanyInfoAndOrders(System.Web.Http.OData.Query.ODataQueryOptions options) {
// Need to handle this specially for NH, to prevent $top being applied to Orders
var query = ContextProvider.Context.Customers;
var queryHelper = new NHQueryHelper();
// apply the $filter, $skip, $top to the query
var query2 = queryHelper.ApplyQuery(query, options);
// execute query, then expand the Orders
var r = query2.Cast<Customer>().ToList();
NHInitializer.InitializeList(r, "Orders");
// after all is loaded, create the projection
var stuff = r.AsQueryable().Select(c => new { c.CompanyName, c.CustomerID, c.Orders });
queryHelper.ConfigureFormatter(Request, query);
#else
public IQueryable<Object> CompanyInfoAndOrders() {
var stuff = ContextProvider.Context.Customers.Select(c => new { c.CompanyName, c.CustomerID, c.Orders });
#endif
return stuff;
}
[HttpGet]
public Object CustomersAndProducts() {
var stuff = new { Customers = ContextProvider.Context.Customers.ToList(), Products = ContextProvider.Context.Products.ToList() };
return stuff;
}
[HttpGet]
public IQueryable<Object> TypeEnvelopes() {
var stuff = this.GetType().Assembly.GetTypes()
.Select(t => new { t.Assembly.FullName, t.Name, t.Namespace })
.AsQueryable();
return stuff;
}
[HttpGet]
public IQueryable<Customer> CustomersAndOrders() {
var custs = ContextProvider.Context.Customers.Include("Orders");
return custs;
}
[HttpGet]
public IQueryable<Order> OrdersAndCustomers() {
var orders = ContextProvider.Context.Orders.Include("Customer");
return orders;
}
[HttpGet]
public IQueryable<Customer> CustomersStartingWithA() {
var custs = ContextProvider.Context.Customers.Where(c => c.CompanyName.StartsWith("A"));
return custs;
}
[HttpGet]
#if NHIBERNATE
[BreezeNHQueryable]
#else
[EnableBreezeQuery]
#endif
public HttpResponseMessage CustomersAsHRM() {
var customers = ContextProvider.Context.Customers.Cast<Customer>();
var response = Request.CreateResponse(HttpStatusCode.OK, customers);
return response;
}
[HttpGet]
public IQueryable<OrderDetail> OrderDetailsMultiple(int multiple, string expands)
{
var query = ContextProvider.Context.OrderDetails.OfType<OrderDetail>();
if (!string.IsNullOrWhiteSpace(expands)) {
var segs = expands.Split(',').ToList();
segs.ForEach(s => {
query = ((System.Data.Entity.Infrastructure.DbQuery<OrderDetail>) query).Include(s);
});
}
var orig = query.ToList();
var list = new List<OrderDetail>(orig.Count * multiple);
for (var i = 0; i < multiple; i++)
{
for (var j = 0; j < orig.Count; j++)
{
var od = orig[j];
var newProductID = i * j + 1;
var clone = new OrderDetail();
clone.Order = od.Order;
clone.OrderID = od.OrderID;
clone.RowVersion = od.RowVersion;
clone.UnitPrice = od.UnitPrice;
clone.Quantity = (short)multiple;
clone.Discount = i;
clone.ProductID = newProductID;
if (od.Product != null) {
var p = new Product();
var op = od.Product;
p.ProductID = newProductID;
p.Category = op.Category;
p.CategoryID = op.CategoryID;
p.Discontinued = op.Discontinued;
p.DiscontinuedDate = op.DiscontinuedDate;
p.ProductName = op.ProductName;
p.QuantityPerUnit = op.QuantityPerUnit;
p.ReorderLevel = op.ReorderLevel;
p.RowVersion = op.RowVersion;
p.Supplier = op.Supplier;
p.SupplierID = op.SupplierID;
p.UnitPrice = op.UnitPrice;
p.UnitsInStock = op.UnitsInStock;
p.UnitsOnOrder = op.UnitsOnOrder;
clone.Product = p;
}
list.Add(clone);
}
}
return list.AsQueryable();
}
#endregion
}
#if CODEFIRST_PROVIDER
public class NorthwindContextProvider : EFContextProvider<NorthwindIBContext_CF> {
public const string CONFIG_VERSION = "CODEFIRST_PROVIDER";
public NorthwindContextProvider() : base() { }
#elif DATABASEFIRST_OLD
public class NorthwindContextProvider: EFContextProvider<NorthwindIBContext_EDMX> {
public const string CONFIG_VERSION = "DATABASEFIRST_OLD";
public NorthwindContextProvider() : base() { }
#elif DATABASEFIRST_NEW
public class NorthwindContextProvider : EFContextProvider<NorthwindIBContext_EDMX_2012> {
public const string CONFIG_VERSION = "DATABASEFIRST_NEW";
public NorthwindContextProvider() : base() { }
#elif ORACLE_EDMX
public class NorthwindContextProvider : EFContextProvider<NorthwindIBContext_EDMX_Oracle> {
public const string CONFIG_VERSION = "ORACLE_EDMX";
public NorthwindContextProvider() : base() { }
#elif NHIBERNATE
public class NorthwindContextProvider : NorthwindNHContext {
public const string CONFIG_VERSION = "NHIBERNATE";
#endif
protected override void AfterSaveEntities(Dictionary<Type, List<EntityInfo>> saveMap, List<KeyMapping> keyMappings) {
var tag = (string)SaveOptions.Tag;
if (tag == "CommentKeyMappings.After") {
foreach (var km in keyMappings) {
var realint = Convert.ToInt32(km.RealValue);
byte seq = (byte)(realint % 512);
AddComment(km.EntityTypeName + ':' + km.RealValue, seq);
}
} else if (tag == "UpdateProduceKeyMapping.After") {
if (!keyMappings.Any()) throw new Exception("UpdateProduce.After: No key mappings available");
var km = keyMappings[0];
UpdateProduceDescription(km.EntityTypeName + ':' + km.RealValue);
} else if (tag == "LookupEmployeeInSeparateContext.After") {
LookupEmployeeInSeparateContext(false);
} else if (tag == "LookupEmployeeInSeparateContext.SameConnection.After") {
LookupEmployeeInSeparateContext(true);
} else if (tag == "deleteProductOnServer") {
var t = typeof(Product);
var prodinfo = saveMap[t].First();
prodinfo.EntityState = EntityState.Deleted;
} else if (tag != null && tag.StartsWith("deleteProductOnServer:")) {
// create new EntityInfo for entity that we want to delete that was not in the save bundle
var id = tag.Substring(tag.IndexOf(':') + 1);
var product = new Product();
product.ProductID = int.Parse(id);
var infos = GetEntityInfos(saveMap, typeof(Product));
var info = CreateEntityInfo(product, EntityState.Deleted);
infos.Add(info);
} else if (tag == "deleteSupplierAndProductOnServer") {
// mark deleted entities that are in the save bundle
var t = typeof(Product);
var infos = GetEntityInfos(saveMap, typeof(Product));
var prodinfo = infos.FirstOrDefault();
if (prodinfo != null) prodinfo.EntityState = EntityState.Deleted;
infos = GetEntityInfos(saveMap, typeof(Supplier));
var supinfo = infos.FirstOrDefault();
if (supinfo != null) supinfo.EntityState = EntityState.Deleted;
}
base.AfterSaveEntities(saveMap, keyMappings);
}
public List<EntityInfo> GetEntityInfos(Dictionary<Type, List<EntityInfo>> saveMap, Type t) {
List<EntityInfo> entityInfos;
if (!saveMap.TryGetValue(t, out entityInfos)) {
entityInfos = new List<EntityInfo>();
saveMap.Add(t, entityInfos);
}
return entityInfos;
}
public Dictionary<Type, List<EntityInfo>> GetSaveMapFromSaveBundle(JObject saveBundle) {
InitializeSaveState(saveBundle); // Sets initial EntityInfos
SaveWorkState.BeforeSave(); // Creates the SaveMap as byproduct of BeforeSave logic
return SaveWorkState.SaveMap;
}
#if (CODEFIRST_PROVIDER || DATABASEFIRST_NEW || DATABASEFIRST_OLD)
/* hack to set the current DbTransaction onto the DbCommand. Transaction comes from EF private properties. */
public void SetCurrentTransaction(System.Data.Common.DbCommand command) {
if (EntityTransaction != null) {
// get private member via reflection
var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
var etype = EntityTransaction.GetType();
var stProp = etype.GetProperty("StoreTransaction", bindingFlags);
var transaction = stProp.GetValue(EntityTransaction, null);
var dbTransaction = transaction as System.Data.Common.DbTransaction;
if (dbTransaction != null) {
command.Transaction = dbTransaction;
}
}
}
#endif
// Test performing a raw db insert to NorthwindIB using the base connection
private int AddComment(string comment, byte seqnum) {
#if ORACLE_EDMX
var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var text = String.Format("insert into COMMENT_ (CreatedOn, Comment1, SeqNum) values (TO_DATE('{0}','YYYY-MM-DD HH24:MI:SS'), '{1}', {2})",
time, comment, seqnum);
#else
var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
var text = String.Format("insert into Comment (CreatedOn, Comment1, SeqNum) values ('{0}', '{1}', {2})",
time, comment, seqnum);
#endif
#if NHIBERNATE
var cmd = Session.CreateSQLQuery(text);
var result = cmd.ExecuteUpdate();
#else
var conn = StoreConnection;
var cmd = conn.CreateCommand();
#if !ORACLE_EDMX
SetCurrentTransaction(cmd);
#endif
cmd.CommandText = text;
var result = cmd.ExecuteNonQuery();
#endif
return result;
}
// Test performing a raw db update to ProduceTPH using the ProduceTPH connection. Requires DTC.
private int UpdateProduceDescription(string comment) {
using (var conn = new SqlConnection("data source=.;initial catalog=ProduceTPH;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework")) {
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = String.Format("update ItemOfProduce set Description='{0}' where id='{1}'",
comment, "13F1C9F5-3189-45FA-BA6E-13314FAFAA92");
var result = cmd.ExecuteNonQuery();
conn.Close();
return result;
}
}
// Use another Context to simulate lookup. Returns Margaret Peacock if employeeId is not specified.
private Employee LookupEmployeeInSeparateContext(bool existingConnection, int employeeId = 4) {
var context2 = existingConnection
#if CODEFIRST_PROVIDER
? new NorthwindIBContext_CF(EntityConnection)
: new NorthwindIBContext_CF();
#elif DATABASEFIRST_OLD
? new NorthwindIBContext_EDMX((System.Data.EntityClient.EntityConnection)EntityConnection)
: new NorthwindIBContext_EDMX();
#elif DATABASEFIRST_NEW
? new NorthwindIBContext_EDMX_2012(EntityConnection)
: new NorthwindIBContext_EDMX_2012();
#elif ORACLE_EDMX
? new NorthwindIBContext_EDMX_Oracle(EntityConnection)
: new NorthwindIBContext_EDMX_Oracle();
#elif NHIBERNATE
? new NorthwindNHContext(this)
: new NorthwindNHContext();
#endif
var query = context2.Employees.Where(e => e.EmployeeID == employeeId);
var employee = query.FirstOrDefault();
return employee;
}
protected override bool BeforeSaveEntity(EntityInfo entityInfo) {
if ((string)SaveOptions.Tag == "addProdOnServer") {
Supplier supplier = entityInfo.Entity as Supplier;
Product product = new Product() {
ProductName = "Product added on server"
};
#if CODEFIRST_PROVIDER
if (supplier.Products == null) supplier.Products = new List<Product>();
#endif
supplier.Products.Add(product);
return true;
}
// prohibit any additions of entities of type 'Region'
if (entityInfo.Entity.GetType() == typeof(Region) && entityInfo.EntityState == EntityState.Added) {
var region = entityInfo.Entity as Region;
if (region.RegionDescription.ToLowerInvariant().StartsWith("error")) return false;
}
#if ORACLE_EDMX
// Convert GUIDs in Customer and Order to be compatible with Oracle
if (entityInfo.Entity.GetType() == typeof(Customer)) {
var cust = entityInfo.Entity as Customer;
if (cust.CustomerID != null) {
cust.CustomerID = cust.CustomerID.ToUpperInvariant();
}
} else if (entityInfo.Entity.GetType() == typeof(Order)) {
var order = entityInfo.Entity as Order;
if (order.CustomerID != null) {
order.CustomerID = order.CustomerID.ToUpperInvariant();
}
}
#endif
return base.BeforeSaveEntity(entityInfo);
}
protected override Dictionary<Type, List<EntityInfo>> BeforeSaveEntities(Dictionary<Type, List<EntityInfo>> saveMap) {
var tag = (string)SaveOptions.Tag;
if (tag == "CommentOrderShipAddress.Before") {
var orderInfos = saveMap[typeof(Order)];
byte seq = 1;
foreach (var info in orderInfos) {
var order = (Order)info.Entity;
AddComment(order.ShipAddress, seq++);
}
} else if (tag == "UpdateProduceShipAddress.Before") {
var orderInfos = saveMap[typeof(Order)];