基于entityframework t4 .tt生成代码模板
平时有一些重复性的工作,然后利用t4模板写了以下代码,希望对大家有用。
1. 生成dal helper 增删改查
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 | <#@ template language= "C#" debug= "false" hostspecific= "true" #> <#@ include file= "EF6.Utility.CS.ttinclude" #><#@ output extension= ".cs" #><# const string inputFile = @"../MS.Organization.Data/Model.edmx" ; var textTransform = DynamicTextTransformation.Create( this ); var code = new CodeGenerationTools( this ); var ef = new MetadataTools( this ); var typeMapper = new TypeMapper(code, ef, textTransform.Errors); var fileManager = EntityFrameworkTemplateFileManager.Create( this ); var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile); var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile)) { return string .Empty; } var container = itemCollection.OfType<EntityContainer>().FirstOrDefault(); if (container == null ) { return string .Empty; } WriteHeader(codeStringGenerator, fileManager); foreach ( var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection)) { var tempClassName = entity.Name + "Helper" ; fileManager.StartNewFile(tempClassName+ ".cs" ); BeginNamespace(code); #> <#=codeStringGenerator.UsingDirectives(inHeader: false , entityType:entity)#> <#=codeStringGenerator.EntityClassOpening(entity, tempClassName)#> <# var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity); var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity); var complexProperties = typeMapper.GetComplexProperties(entity); #> { <# var simpleProperties = typeMapper.GetSimpleProperties(entity);; if (simpleProperties.Any()) { #> /// <summary> /// 新增 <#= entity.Name #> /// </summary> /// <param name="<#= entity.Name.ToLower() #>"><#= entity.Name #>的实例</param> /// <returns></returns> public static JsonModelHelper.JsonModel Add(<#= entity.Name #> <#= entity.Name.ToLower() #>, out string hyUniqueId) { try { hyUniqueId = Guid.NewGuid().ToString(); using (<#=container.Name#> entities = new <#=container.Name#>()) { <#= entity.Name.ToLower() #>.HYUniqueID = hyUniqueId; entities.<#= entity.Name #>.Add( <#= entity.Name.ToLower() #>); entities.SaveChanges(); } return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Success, Information = "成功" }; } catch (Exception ex) { hyUniqueId = "" ; return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Exception, Information = "异常" , Data = ex }; } } /// <summary> /// 删除 <#= entity.Name #> /// </summary> /// <param name="<#= entity.Name.ToLower() #>"><#= entity.Name #>的实例</param> /// <returns></returns> public static JsonModelHelper.JsonModel Remove(<#= entity.Name #> <#= entity.Name.ToLower() #>) { if (<#= entity.Name.ToLower() #> == null ) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" , Data = "<#= entity.Name.ToLower() #>为空" }; } try { using (<#=container.Name#> entities = new <#=container.Name#>()) { entities.Configuration.UseDatabaseNullSemantics = true ; var entity = entities.<#= entity.Name #>.Where(b => b.ID == <#= entity.Name.ToLower() #>.ID || b.HYUniqueID == <#= entity.Name.ToLower() #>.HYUniqueID).FirstOrDefault(); if (entity == null ) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败,不存在此记录" }; } entities.<#= entity.Name #>.Remove(entity); entities.SaveChanges(); } return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Success, Information = "成功" }; } catch (Exception ex) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Exception, Information = "异常" , Data = ex }; } } /// <summary> /// 修改 <#= entity.Name #> /// </summary> /// <param name="<#= entity.Name.ToLower() #>"><#= entity.Name #>的实例</param> /// <returns></returns> public static JsonModelHelper.JsonModel Update(<#= entity.Name #> <#= entity.Name.ToLower() #>) { if (<#= entity.Name.ToLower() #> == null ) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" , Data = "<#= entity.Name.ToLower() #>为空" }; } try { using (<#=container.Name#> entities = new <#=container.Name#>()) { entities.Configuration.UseDatabaseNullSemantics = true ; var oldEntity = entities.<#= entity.Name #>.AsNoTracking().Where(c => c.HYUniqueID == <#= entity.Name.ToLower() #>.HYUniqueID).FirstOrDefault(); if (oldEntity == null ) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "错误" }; } <#= entity.Name.ToLower() #>.HYUniqueID = oldEntity.HYUniqueID; <#= entity.Name.ToLower() #>.ID = oldEntity.ID; var entry = entities.Entry<<#= entity.Name #>>(<#= entity.Name.ToLower() #>); entry.State = System.Data.Entity.EntityState.Modified; entities.SaveChanges(); } return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Success, Information = "成功" }; } catch (Exception ex) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Exception, Information = "异常" , Data = ex }; } } /// <summary> /// 查询 <#= entity.Name #> /// </summary> /// <param name="whereLambda">查询条件</param> /// <param name="data">返回数据(集合)</param> /// <param name="pageSize">页大小</param> /// <param name="pageIndex">页索引</param> /// <param name="sortField">排序字段</param> /// <param name="sortDirection">排序方式 desc asc</param> /// <returns></returns> public static JsonModelHelper.JsonModel Find(Func<<#= entity.Name #>, bool > whereLambda, out List<<#= entity.Name #>> data, int ? pageSize = 0, int ? pageIndex = 0, string sortField = "" , string sortDirection = "" ) //实现分页的方法 { sortDirection = sortDirection.ToLower(); data = null ; if (whereLambda == null ) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" , Data = "whereLambda为空" }; } try { using (<#=container.Name#> entities = new <#=container.Name#>()) { entities.Configuration.UseDatabaseNullSemantics = true ; IQueryable<<#= entity.Name #>> query = null ; switch (sortField) { <# foreach ( var edmProperty in simpleProperties) { #> case "<#= edmProperty.Name #>" : query = (sortDirection == "ascending" ? entities.<#= entity.Name #>.OrderBy(c => c.<#= edmProperty.Name #>) : entities.<#= entity.Name #>.OrderByDescending(c => c.<#= edmProperty.Name #>)); break ; <# } #> default : query = (sortDirection == "ascending" ? entities.<#= entity.Name #>.OrderBy(c => c.CreateTime) : entities.<#= entity.Name #>.OrderByDescending(c => c.CreateTime)); break ; } data =query.Where<<#= entity.Name #>>(whereLambda) .Skip<<#= entity.Name #>>(pageSize.Value * (pageIndex.Value - 1)) .Take<<#= entity.Name #>>(pageSize ?? 1000) .AsQueryable<<#= entity.Name #>>().ToList(); } return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Success, Information = "成功" , Data = data }; } catch (Exception ex) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Exception, Information = "异常" , Data = ex }; } } /// <summary> /// 查询 <#= entity.Name #>的Count /// </summary> /// <param name="whereLambda">条件</param> /// <param name="count">返回值Count</param> /// <returns></returns> public static JsonModelHelper.JsonModel GetCount(Func<<#= entity.Name #>, bool > whereLambda, out int count) { count = 0; if (whereLambda == null ) { whereLambda = e => { return true ; }; } try { using (<#=container.Name#> entities = new <#=container.Name#>()) { entities.Configuration.UseDatabaseNullSemantics = true ; count = entities.<#= entity.Name #>.Where<<#= entity.Name #>>(whereLambda) .AsQueryable<<#= entity.Name #>>().Count(); } return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Success, Information = "成功" }; } catch (Exception ex) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Exception, Information = "异常" , Data = ex }; } } #region 字段 <# foreach ( var edmProperty in simpleProperties) { #> //<#=entity.Name.ToLower()+"."+edmProperty.Name #> <# } } if (complexProperties.Any()) { #> <# foreach ( var complexProperty in complexProperties) { #> <#=codeStringGenerator.Property(complexProperty)#> <# } } var navigationProperties = typeMapper.GetNavigationProperties(entity); if (navigationProperties.Any()) { #> <# foreach ( var navigationProperty in navigationProperties) { if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many) { #> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage" , "CA2227:CollectionPropertiesShouldBeReadOnly" )] <# } #> <#=codeStringGenerator.NavigationProperty(navigationProperty)#> <# } } #> #endregion <#= "}" #> <# EndNamespace(code); } foreach ( var complex in typeMapper.GetItemsToGenerate<ComplexType>(itemCollection)) { fileManager.StartNewFile(complex.Name + ".cs" ); BeginNamespace(code); #> <#=codeStringGenerator.UsingDirectives(inHeader: false , includeCollections: false )#> <#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#> { <# var complexProperties = typeMapper.GetComplexProperties(complex); var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(complex); if (propertiesWithDefaultValues.Any() || complexProperties.Any()) { #> public <#=code.Escape(complex)#>() { <# foreach ( var edmProperty in propertiesWithDefaultValues) { #> this .<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>; <# } foreach ( var complexProperty in complexProperties) { #> this .<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>(); <# } #> } <# } var simpleProperties = typeMapper.GetSimpleProperties(complex); if (simpleProperties.Any()) { foreach ( var edmProperty in simpleProperties) { #> <#=codeStringGenerator.Property(edmProperty)#> <# } } if (complexProperties.Any()) { #> <# foreach ( var edmProperty in complexProperties) { #> <#=codeStringGenerator.Property(edmProperty)#> <# } } #> } <# EndNamespace(code); } foreach ( var enumType in typeMapper.GetEnumItemsToGenerate(itemCollection)) { fileManager.StartNewFile(enumType.Name + ".cs" ); BeginNamespace(code); #> <#=codeStringGenerator.UsingDirectives(inHeader: false , includeCollections: false )#> <# if (typeMapper.EnumIsFlags(enumType)) { #> [Flags] <# } #> <#=codeStringGenerator.EnumOpening(enumType)#> { <# var foundOne = false ; foreach (MetadataItem member in typeMapper.GetEnumMembers(enumType)) { foundOne = true ; #> <#=code.Escape(typeMapper.GetEnumMemberName(member))#> = <#=typeMapper.GetEnumMemberValue(member)#>, <# } if (foundOne) { this .GenerationEnvironment.Remove( this .GenerationEnvironment.Length - 3, 1); } #> } <# EndNamespace(code); } fileManager.Process(); #> <#+ public void WriteHeader(CodeStringGenerator codeStringGenerator, EntityFrameworkTemplateFileManager fileManager) { fileManager.StartHeader(); #> //------------------------------------------------------------------------------ // <auto-generated> // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")#> // // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")#> // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")#> // </auto-generated> //------------------------------------------------------------------------------ <#=codeStringGenerator.UsingDirectives(inHeader: true )#> <#+ fileManager.EndBlock(); } public void BeginNamespace(CodeGenerationTools code) { var codeNamespace = code.VsNamespaceSuggestion(); if (!String.IsNullOrEmpty(codeNamespace)) { #> namespace <#=code.EscapeNamespace(codeNamespace)#> { <#+ PushIndent( " " ); } } public void EndNamespace(CodeGenerationTools code) { if (!String.IsNullOrEmpty(code.VsNamespaceSuggestion())) { PopIndent(); #> } <#+ } } public const string TemplateId = "CSharp_DbContext_Types_EF6" ; public class CodeStringGenerator { private readonly CodeGenerationTools _code; private readonly TypeMapper _typeMapper; private readonly MetadataTools _ef; //预设置要导入的包 private string prePackages = "\r\n" + "using DM2.DMP.Common; " + "\r\n" + "using DM2.DMP.WebCommon; " + "\r\n" + "using Data; " + "\r\n" + "using Helper; " + "\r\n" + "using System.Linq; " ; public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) { ArgumentNotNull(code, "code" ); ArgumentNotNull(typeMapper, "typeMapper" ); ArgumentNotNull(ef, "ef" ); _code = code; _typeMapper = typeMapper; _ef = ef; } public string Property(EdmProperty edmProperty) { return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}" , Accessibility.ForProperty(edmProperty), _typeMapper.GetTypeName(edmProperty.TypeUsage), _code.Escape(edmProperty), _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); } public string NavigationProperty(NavigationProperty navProp) { var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType()); return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}" , AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)), navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ( "ICollection<" + endType + ">" ) : endType, _code.Escape(navProp), _code.SpaceAfter(Accessibility.ForGetter(navProp)), _code.SpaceAfter(Accessibility.ForSetter(navProp))); } public string AccessibilityAndVirtual( string accessibility) { return accessibility + (accessibility != "private" ? " virtual" : "" ); } public string EntityClassOpening(EntityType entity, string entityName = null ) { return string .Format( CultureInfo.InvariantCulture, "{0} {1}partial class {2}{3}" , Accessibility.ForType(entity), _code.SpaceAfter(_code.AbstractOption(entity)), entityName = (entityName == null ? _code.Escape(entity) : entityName), _code.StringBefore( " : " , "" )); } public string EnumOpening(SimpleType enumType) { return string .Format( CultureInfo.InvariantCulture, "{0} enum {1} : {2}" , Accessibility.ForType(enumType), _code.Escape(enumType), _code.Escape(_typeMapper.UnderlyingClrType(enumType))); } public void WriteFunctionParameters(EdmFunction edmFunction, Action< string , string , string , string > writeParameter) { var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); foreach ( var parameter in parameters.Where(p => p.NeedsLocalVariable)) { var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null" ; var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")" ; var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))" ; writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); } } public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) { var parameters = _typeMapper.GetParameters(edmFunction); return string .Format( CultureInfo.InvariantCulture, "{0} IQueryable<{1}> {2}({3})" , AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), _code.Escape(edmFunction), string .Join( ", " , parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray())); } public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) { var parameters = _typeMapper.GetParameters(edmFunction); return string .Format( CultureInfo.InvariantCulture, "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});" , _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), edmFunction.NamespaceName, edmFunction.Name, string .Join( ", " , parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), _code.StringBefore( ", " , string .Join( ", " , parameters.Select(p => p.ExecuteParameterName).ToArray()))); } public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) { var parameters = _typeMapper.GetParameters(edmFunction); var returnType = _typeMapper.GetReturnType(edmFunction); var paramList = String.Join( ", " , parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()); if (includeMergeOption) { paramList = _code.StringAfter(paramList, ", " ) + "MergeOption mergeOption" ; } return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2}({3})" , AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">" , _code.Escape(edmFunction), paramList); } public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) { var parameters = _typeMapper.GetParameters(edmFunction); var returnType = _typeMapper.GetReturnType(edmFunction); var callParams = _code.StringBefore( ", " , String.Join( ", " , parameters.Select(p => p.ExecuteParameterName).ToArray())); if (includeMergeOption) { callParams = ", mergeOption" + callParams; } return string .Format( CultureInfo.InvariantCulture, "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});" , returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">" , edmFunction.Name, callParams); } public string DbSet(EntitySet entitySet) { return string .Format( CultureInfo.InvariantCulture, "{0} virtual DbSet<{1}> {2} {{ get; set; }}" , Accessibility.ForReadOnlyProperty(entitySet), _typeMapper.GetTypeName(entitySet.ElementType), _code.Escape(entitySet)); } public string UsingDirectives( bool inHeader, bool includeCollections = true , EntityType entityType = null ) { var directives = inHeader == string .IsNullOrEmpty(_code.VsNamespaceSuggestion()) ? string .Format( CultureInfo.InvariantCulture, "{0}using System;{1}" + "{2}" , inHeader ? Environment.NewLine : "" , includeCollections ? (Environment.NewLine + "using System.Collections.Generic;" ) : "" , inHeader ? "" : Environment.NewLine) : "" ; if (directives == "" ) { return directives; } if (entityType != null ) { prePackages = prePackages.Replace( "{entityType}" ,entityType.Name).Replace( "_" , "" ); } directives+= "\r\n" +prePackages; return directives; } } public class TypeMapper { private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName" ; private readonly System.Collections.IList _errors; private readonly CodeGenerationTools _code; private readonly MetadataTools _ef; public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) { ArgumentNotNull(code, "code" ); ArgumentNotNull(ef, "ef" ); ArgumentNotNull(errors, "errors" ); _code = code; _ef = ef; _errors = errors; } public static string FixNamespaces( string typeName) { return typeName.Replace( "System.Data.Spatial." , "System.Data.Entity.Spatial." ); } public string GetTypeName(TypeUsage typeUsage) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null ); } public string GetTypeName(EdmType edmType) { return GetTypeName(edmType, isNullable: null , modelNamespace: null ); } public string GetTypeName(TypeUsage typeUsage, string modelNamespace) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); } public string GetTypeName(EdmType edmType, string modelNamespace) { return GetTypeName(edmType, isNullable: null , modelNamespace: modelNamespace); } public string GetTypeName(EdmType edmType, bool ? isNullable, string modelNamespace) { if (edmType == null ) { return null ; } var collectionType = edmType as CollectionType; if (collectionType != null ) { return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>" , GetTypeName(collectionType.TypeUsage, modelNamespace)); } var typeName = _code.Escape(edmType.MetadataProperties .Where(p => p.Name == ExternalTypeNameAttributeName) .Select(p => ( string )p.Value) .FirstOrDefault()) ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : _code.Escape(edmType)); if (edmType is StructuralType) { return typeName; } if (edmType is SimpleType) { var clrType = UnderlyingClrType(edmType); if (!IsEnumType(edmType)) { typeName = _code.Escape(clrType); } typeName = FixNamespaces(typeName); return clrType.IsValueType && isNullable == true ? String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>" , typeName) : typeName; } throw new ArgumentException( "edmType" ); } public Type UnderlyingClrType(EdmType edmType) { ArgumentNotNull(edmType, "edmType" ); var primitiveType = edmType as PrimitiveType; if (primitiveType != null ) { return primitiveType.ClrEquivalentType; } if (IsEnumType(edmType)) { return GetEnumUnderlyingType(edmType).ClrEquivalentType; } return typeof ( object ); } public object GetEnumMemberValue(MetadataItem enumMember) { ArgumentNotNull(enumMember, "enumMember" ); var valueProperty = enumMember.GetType().GetProperty( "Value" ); return valueProperty == null ? null : valueProperty.GetValue(enumMember, null ); } public string GetEnumMemberName(MetadataItem enumMember) { ArgumentNotNull(enumMember, "enumMember" ); var nameProperty = enumMember.GetType().GetProperty( "Name" ); return nameProperty == null ? null : ( string )nameProperty.GetValue(enumMember, null ); } public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); var membersProperty = enumType.GetType().GetProperty( "Members" ); return membersProperty != null ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null ) : Enumerable.Empty<MetadataItem>(); } public bool EnumIsFlags(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); var isFlagsProperty = enumType.GetType().GetProperty( "IsFlags" ); return isFlagsProperty != null && ( bool )isFlagsProperty.GetValue(enumType, null ); } public bool IsEnumType(GlobalItem edmType) { ArgumentNotNull(edmType, "edmType" ); return edmType.GetType().Name == "EnumType" ; } public PrimitiveType GetEnumUnderlyingType(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); return (PrimitiveType)enumType.GetType().GetProperty( "UnderlyingType" ).GetValue(enumType, null ); } public string CreateLiteral( object value) { if (value == null || value.GetType() != typeof (TimeSpan)) { return _code.CreateLiteral(value); } return string .Format(CultureInfo.InvariantCulture, "new TimeSpan({0})" , ((TimeSpan)value).Ticks); } public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable< string > types, string sourceFile) { ArgumentNotNull(types, "types" ); ArgumentNotNull(sourceFile, "sourceFile" ); var hash = new HashSet< string >(StringComparer.InvariantCultureIgnoreCase); if (types.Any(item => !hash.Add(item))) { _errors.Add( new CompilerError(sourceFile, -1, -1, "6023" , String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString( "Template_CaseInsensitiveTypeConflict" )))); return false ; } return true ; } public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection) { return GetItemsToGenerate<SimpleType>(itemCollection) .Where(e => IsEnumType(e)); } public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType { return itemCollection .OfType<T>() .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) .OrderBy(i => i.Name); } public IEnumerable< string > GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection) { return itemCollection .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) .Select(g => GetGlobalItemName(g)); } public string GetGlobalItemName(GlobalItem item) { if (item is EdmType) { return ((EdmType)item).Name; } else { return ((EntityContainer)item).Name; } } public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetComplexProperties(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null ); } public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null ); } public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type) { return type.NavigationProperties.Where(np => np.DeclaringType == type); } public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type) { return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); } public FunctionParameter GetReturnParameter(EdmFunction edmFunction) { ArgumentNotNull(edmFunction, "edmFunction" ); var returnParamsProperty = edmFunction.GetType().GetProperty( "ReturnParameters" ); return returnParamsProperty == null ? edmFunction.ReturnParameter : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null )).FirstOrDefault(); } public bool IsComposable(EdmFunction edmFunction) { ArgumentNotNull(edmFunction, "edmFunction" ); var isComposableProperty = edmFunction.GetType().GetProperty( "IsComposableAttribute" ); return isComposableProperty != null && ( bool )isComposableProperty.GetValue(edmFunction, null ); } public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction) { return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); } public TypeUsage GetReturnType(EdmFunction edmFunction) { var returnParam = GetReturnParameter(edmFunction); return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); } public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) { var returnType = GetReturnType(edmFunction); return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; } } public static void ArgumentNotNull<T>(T arg, string name) where T : class { if (arg == null ) { throw new ArgumentNullException(name); } } #> |
2. 生成web层的 webapicontroller
生成addcontroller
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 | <#@ template language= "C#" debug= "false" hostspecific= "true" #> <#@ include file= "EF6.Utility.CS.ttinclude" #><#@ output extension= ".cs" #> <# const string inputFile = @"../../MS.Brand.Data/Model.edmx" ; var textTransform = DynamicTextTransformation.Create( this ); var code = new CodeGenerationTools( this ); var ef = new MetadataTools( this ); var typeMapper = new TypeMapper(code, ef, textTransform.Errors); var fileManager = EntityFrameworkTemplateFileManager.Create( this ); var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile); var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile)) { return string .Empty; } var container = itemCollection.OfType<EntityContainer>().FirstOrDefault(); if (container == null ) { return string .Empty; } //----------------------------BEGIN ADD------------------------------------------ WriteHeader(codeStringGenerator, fileManager); foreach ( var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection)) { var tempClassName = "Add" +entity.Name + "Controller" ; fileManager.StartNewFile(tempClassName+ ".cs" ); BeginNamespace(code); #> <#=codeStringGenerator.UsingDirectives(inHeader: false , entityType:entity)#> <#=codeStringGenerator.EntityClassOpening(entity, tempClassName)#> { <# var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity); var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity); var complexProperties = typeMapper.GetComplexProperties(entity); #> <# var simpleProperties = typeMapper.GetSimpleProperties(entity);; if (simpleProperties.Any()) { #> HttpContextBase Context = null ; /// <summary> /// 新增 <#= entity.Name #> /// </summary> /// <param name="<#= entity.Name.ToLower() #>"><#= entity.Name #>的实例</param> /// <returns></returns> public JsonModelHelper.JsonModel Post(<#= entity.Name #> <#= entity.Name.ToLower() #>) { Context = (HttpContextBase)Request.Properties[ "MS_HttpContext" ]; try { var hyUniqueId = string .Empty; var result = <#= entity.Name #>Helper.Add(<#= entity.Name.ToLower() #>, out hyUniqueId); if (result == null ) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" }; } if (result.Status != JsonModelHelper.EJsonModel.Success) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" , Data = result.Data }; } return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Success, Information = "成功" , Data= new {id = hyUniqueId} }; } catch (Exception ex) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Exception, Information = "异常" , Data = ex }; } } #region 字段 <# foreach ( var edmProperty in simpleProperties) { #> //<#=entity.Name.ToLower()+"."+edmProperty.Name #> <# } } if (complexProperties.Any()) { #> <# foreach ( var complexProperty in complexProperties) { #> <#=codeStringGenerator.Property(complexProperty)#> <# } } var navigationProperties = typeMapper.GetNavigationProperties(entity); if (navigationProperties.Any()) { #> <# foreach ( var navigationProperty in navigationProperties) { if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many) { #> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage" , "CA2227:CollectionPropertiesShouldBeReadOnly" )] <# } #> <#=codeStringGenerator.NavigationProperty(navigationProperty)#> <# } } #> #endregion <#= "}" #> <# EndNamespace(code); } fileManager.Process(); #> //----------------------------END ADD------------------------------------------ <#+ public void WriteHeader(CodeStringGenerator codeStringGenerator, EntityFrameworkTemplateFileManager fileManager) { fileManager.StartHeader(); #> //------------------------------------------------------------------------------ // <auto-generated> // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")#> // // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")#> // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")#> // </auto-generated> //------------------------------------------------------------------------------ <#=codeStringGenerator.UsingDirectives(inHeader: true )#> <#+ fileManager.EndBlock(); } public void BeginNamespace(CodeGenerationTools code) { var codeNamespace = code.VsNamespaceSuggestion(); if (!String.IsNullOrEmpty(codeNamespace)) { #> namespace <#=code.EscapeNamespace(codeNamespace)#> { <#+ PushIndent( " " ); } } public void EndNamespace(CodeGenerationTools code) { if (!String.IsNullOrEmpty(code.VsNamespaceSuggestion())) { PopIndent(); #> } <#+ } } public const string TemplateId = "CSharp_DbContext_Types_EF6" ; public class CodeStringGenerator { private readonly CodeGenerationTools _code; private readonly TypeMapper _typeMapper; private readonly MetadataTools _ef; //预设置要导入的包 private string prePackages = "\r\n" + "using DM2.DMP.Common; " + "\r\n" + "using DM2.DMP.WebCommon; " + "\r\n" + "using Data; " + "\r\n" + "using Helper; " + "\r\n" + "using System; " + "\r\n" + "using System.Collections.Generic;" + "\r\n" + "using System.Linq; " + "\r\n" + "using System.Net; " + "\r\n" + "using System.Net.Http; " + "\r\n" + "using System.Web; " + "\r\n" + "using System.Web.Http; " ; public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) { ArgumentNotNull(code, "code" ); ArgumentNotNull(typeMapper, "typeMapper" ); ArgumentNotNull(ef, "ef" ); _code = code; _typeMapper = typeMapper; _ef = ef; } public string Property(EdmProperty edmProperty) { return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}" , Accessibility.ForProperty(edmProperty), _typeMapper.GetTypeName(edmProperty.TypeUsage), _code.Escape(edmProperty), _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); } public string NavigationProperty(NavigationProperty navProp) { var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType()); return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}" , AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)), navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ( "ICollection<" + endType + ">" ) : endType, _code.Escape(navProp), _code.SpaceAfter(Accessibility.ForGetter(navProp)), _code.SpaceAfter(Accessibility.ForSetter(navProp))); } public string AccessibilityAndVirtual( string accessibility) { return accessibility + (accessibility != "private" ? " virtual" : "" ); } public string EntityClassOpening(EntityType entity, string entityName = null ) { return string .Format( CultureInfo.InvariantCulture, "{0} {1}partial class {2}{3}" , Accessibility.ForType(entity), _code.SpaceAfter(_code.AbstractOption(entity)), entityName = (entityName == null ? _code.Escape(entity) : entityName), _code.StringBefore( " : " , "ApiController" )); } public string EnumOpening(SimpleType enumType) { return string .Format( CultureInfo.InvariantCulture, "{0} enum {1} : {2}" , Accessibility.ForType(enumType), _code.Escape(enumType), _code.Escape(_typeMapper.UnderlyingClrType(enumType))); } public void WriteFunctionParameters(EdmFunction edmFunction, Action< string , string , string , string > writeParameter) { var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); foreach ( var parameter in parameters.Where(p => p.NeedsLocalVariable)) { var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null" ; var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")" ; var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))" ; writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); } } public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) { var parameters = _typeMapper.GetParameters(edmFunction); return string .Format( CultureInfo.InvariantCulture, "{0} IQueryable<{1}> {2}({3})" , AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), _code.Escape(edmFunction), string .Join( ", " , parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray())); } public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) { var parameters = _typeMapper.GetParameters(edmFunction); return string .Format( CultureInfo.InvariantCulture, "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});" , _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), edmFunction.NamespaceName, edmFunction.Name, string .Join( ", " , parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), _code.StringBefore( ", " , string .Join( ", " , parameters.Select(p => p.ExecuteParameterName).ToArray()))); } public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) { var parameters = _typeMapper.GetParameters(edmFunction); var returnType = _typeMapper.GetReturnType(edmFunction); var paramList = String.Join( ", " , parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()); if (includeMergeOption) { paramList = _code.StringAfter(paramList, ", " ) + "MergeOption mergeOption" ; } return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2}({3})" , AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">" , _code.Escape(edmFunction), paramList); } public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) { var parameters = _typeMapper.GetParameters(edmFunction); var returnType = _typeMapper.GetReturnType(edmFunction); var callParams = _code.StringBefore( ", " , String.Join( ", " , parameters.Select(p => p.ExecuteParameterName).ToArray())); if (includeMergeOption) { callParams = ", mergeOption" + callParams; } return string .Format( CultureInfo.InvariantCulture, "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});" , returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">" , edmFunction.Name, callParams); } public string DbSet(EntitySet entitySet) { return string .Format( CultureInfo.InvariantCulture, "{0} virtual DbSet<{1}> {2} {{ get; set; }}" , Accessibility.ForReadOnlyProperty(entitySet), _typeMapper.GetTypeName(entitySet.ElementType), _code.Escape(entitySet)); } public string UsingDirectives( bool inHeader, bool includeCollections = true , EntityType entityType = null ) { var directives = inHeader == string .IsNullOrEmpty(_code.VsNamespaceSuggestion()) ? string .Format( CultureInfo.InvariantCulture, "{0}using System;{1}" + "{2}" , inHeader ? Environment.NewLine : "" , includeCollections ? (Environment.NewLine + "using System.Collections.Generic;" ) : "" , inHeader ? "" : Environment.NewLine) : "" ; if (directives == "" ) { return directives; } if (entityType != null ) { prePackages = prePackages.Replace( "{entityType}" ,entityType.Name).Replace( "_" , "" ); } directives+= "\r\n" +prePackages; return directives; } } public class TypeMapper { private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName" ; private readonly System.Collections.IList _errors; private readonly CodeGenerationTools _code; private readonly MetadataTools _ef; public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) { ArgumentNotNull(code, "code" ); ArgumentNotNull(ef, "ef" ); ArgumentNotNull(errors, "errors" ); _code = code; _ef = ef; _errors = errors; } public static string FixNamespaces( string typeName) { return typeName.Replace( "System.Data.Spatial." , "System.Data.Entity.Spatial." ); } public string GetTypeName(TypeUsage typeUsage) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null ); } public string GetTypeName(EdmType edmType) { return GetTypeName(edmType, isNullable: null , modelNamespace: null ); } public string GetTypeName(TypeUsage typeUsage, string modelNamespace) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); } public string GetTypeName(EdmType edmType, string modelNamespace) { return GetTypeName(edmType, isNullable: null , modelNamespace: modelNamespace); } public string GetTypeName(EdmType edmType, bool ? isNullable, string modelNamespace) { if (edmType == null ) { return null ; } var collectionType = edmType as CollectionType; if (collectionType != null ) { return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>" , GetTypeName(collectionType.TypeUsage, modelNamespace)); } var typeName = _code.Escape(edmType.MetadataProperties .Where(p => p.Name == ExternalTypeNameAttributeName) .Select(p => ( string )p.Value) .FirstOrDefault()) ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : _code.Escape(edmType)); if (edmType is StructuralType) { return typeName; } if (edmType is SimpleType) { var clrType = UnderlyingClrType(edmType); if (!IsEnumType(edmType)) { typeName = _code.Escape(clrType); } typeName = FixNamespaces(typeName); return clrType.IsValueType && isNullable == true ? String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>" , typeName) : typeName; } throw new ArgumentException( "edmType" ); } public Type UnderlyingClrType(EdmType edmType) { ArgumentNotNull(edmType, "edmType" ); var primitiveType = edmType as PrimitiveType; if (primitiveType != null ) { return primitiveType.ClrEquivalentType; } if (IsEnumType(edmType)) { return GetEnumUnderlyingType(edmType).ClrEquivalentType; } return typeof ( object ); } public object GetEnumMemberValue(MetadataItem enumMember) { ArgumentNotNull(enumMember, "enumMember" ); var valueProperty = enumMember.GetType().GetProperty( "Value" ); return valueProperty == null ? null : valueProperty.GetValue(enumMember, null ); } public string GetEnumMemberName(MetadataItem enumMember) { ArgumentNotNull(enumMember, "enumMember" ); var nameProperty = enumMember.GetType().GetProperty( "Name" ); return nameProperty == null ? null : ( string )nameProperty.GetValue(enumMember, null ); } public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); var membersProperty = enumType.GetType().GetProperty( "Members" ); return membersProperty != null ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null ) : Enumerable.Empty<MetadataItem>(); } public bool EnumIsFlags(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); var isFlagsProperty = enumType.GetType().GetProperty( "IsFlags" ); return isFlagsProperty != null && ( bool )isFlagsProperty.GetValue(enumType, null ); } public bool IsEnumType(GlobalItem edmType) { ArgumentNotNull(edmType, "edmType" ); return edmType.GetType().Name == "EnumType" ; } public PrimitiveType GetEnumUnderlyingType(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); return (PrimitiveType)enumType.GetType().GetProperty( "UnderlyingType" ).GetValue(enumType, null ); } public string CreateLiteral( object value) { if (value == null || value.GetType() != typeof (TimeSpan)) { return _code.CreateLiteral(value); } return string .Format(CultureInfo.InvariantCulture, "new TimeSpan({0})" , ((TimeSpan)value).Ticks); } public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable< string > types, string sourceFile) { ArgumentNotNull(types, "types" ); ArgumentNotNull(sourceFile, "sourceFile" ); var hash = new HashSet< string >(StringComparer.InvariantCultureIgnoreCase); if (types.Any(item => !hash.Add(item))) { _errors.Add( new CompilerError(sourceFile, -1, -1, "6023" , String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString( "Template_CaseInsensitiveTypeConflict" )))); return false ; } return true ; } public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection) { return GetItemsToGenerate<SimpleType>(itemCollection) .Where(e => IsEnumType(e)); } public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType { return itemCollection .OfType<T>() .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) .OrderBy(i => i.Name); } public IEnumerable< string > GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection) { return itemCollection .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) .Select(g => GetGlobalItemName(g)); } public string GetGlobalItemName(GlobalItem item) { if (item is EdmType) { return ((EdmType)item).Name; } else { return ((EntityContainer)item).Name; } } public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetComplexProperties(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null ); } public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null ); } public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type) { return type.NavigationProperties.Where(np => np.DeclaringType == type); } public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type) { return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); } public FunctionParameter GetReturnParameter(EdmFunction edmFunction) { ArgumentNotNull(edmFunction, "edmFunction" ); var returnParamsProperty = edmFunction.GetType().GetProperty( "ReturnParameters" ); return returnParamsProperty == null ? edmFunction.ReturnParameter : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null )).FirstOrDefault(); } public bool IsComposable(EdmFunction edmFunction) { ArgumentNotNull(edmFunction, "edmFunction" ); var isComposableProperty = edmFunction.GetType().GetProperty( "IsComposableAttribute" ); return isComposableProperty != null && ( bool )isComposableProperty.GetValue(edmFunction, null ); } public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction) { return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); } public TypeUsage GetReturnType(EdmFunction edmFunction) { var returnParam = GetReturnParameter(edmFunction); return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); } public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) { var returnType = GetReturnType(edmFunction); return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; } } public static void ArgumentNotNull<T>(T arg, string name) where T : class { if (arg == null ) { throw new ArgumentNullException(name); } } #> |
生成updatecontroller
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 | <#@ template language= "C#" debug= "false" hostspecific= "true" #> <#@ include file= "EF6.Utility.CS.ttinclude" #><#@ output extension= ".cs" #> <# const string inputFile = @"../../MS.Brand.Data/Model.edmx" ; var textTransform = DynamicTextTransformation.Create( this ); var code = new CodeGenerationTools( this ); var ef = new MetadataTools( this ); var typeMapper = new TypeMapper(code, ef, textTransform.Errors); var fileManager = EntityFrameworkTemplateFileManager.Create( this ); var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile); var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile)) { return string .Empty; } var container = itemCollection.OfType<EntityContainer>().FirstOrDefault(); if (container == null ) { return string .Empty; } //----------------------------BEGIN Update------------------------------------------ WriteHeader(codeStringGenerator, fileManager); foreach ( var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection)) { var tempClassName = "Update" +entity.Name + "Controller" ; fileManager.StartNewFile(tempClassName+ ".cs" ); BeginNamespace(code); #> <#=codeStringGenerator.UsingDirectives(inHeader: false , entityType:entity)#> <#=codeStringGenerator.EntityClassOpening(entity, tempClassName)#> { <# var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity); var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity); var complexProperties = typeMapper.GetComplexProperties(entity); #> <# var simpleProperties = typeMapper.GetSimpleProperties(entity);; if (simpleProperties.Any()) { #> HttpContextBase Context = null ; /// <summary> /// 更新 <#= entity.Name #> /// </summary> /// <param name="<#= entity.Name.ToLower() #>"><#= entity.Name #>的实例</param> /// <returns></returns> public JsonModelHelper.JsonModel Post(<#= entity.Name #> <#= entity.Name.ToLower() #>) { Context = (HttpContextBase)Request.Properties[ "MS_HttpContext" ]; try { var result = <#= entity.Name #>Helper.Update(<#= entity.Name.ToLower() #>); if (result == null ) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" }; } if (result.Status != JsonModelHelper.EJsonModel.Success) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" , Data = result.Data }; } return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Success, Information = "成功" }; } catch (Exception ex) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Exception, Information = "异常" , Data = ex }; } } #region 字段 <# foreach ( var edmProperty in simpleProperties) { #> //<#=entity.Name.ToLower()+"."+edmProperty.Name #> <# } } if (complexProperties.Any()) { #> <# foreach ( var complexProperty in complexProperties) { #> <#=codeStringGenerator.Property(complexProperty)#> <# } } var navigationProperties = typeMapper.GetNavigationProperties(entity); if (navigationProperties.Any()) { #> <# foreach ( var navigationProperty in navigationProperties) { if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many) { #> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage" , "CA2227:CollectionPropertiesShouldBeReadOnly" )] <# } #> <#=codeStringGenerator.NavigationProperty(navigationProperty)#> <# } } #> #endregion <#= "}" #> <# EndNamespace(code); } fileManager.Process(); #> //----------------------------END Update------------------------------------------ <#+ public void WriteHeader(CodeStringGenerator codeStringGenerator, EntityFrameworkTemplateFileManager fileManager) { fileManager.StartHeader(); #> //------------------------------------------------------------------------------ // <auto-generated> // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")#> // // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")#> // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")#> // </auto-generated> //------------------------------------------------------------------------------ <#=codeStringGenerator.UsingDirectives(inHeader: true )#> <#+ fileManager.EndBlock(); } public void BeginNamespace(CodeGenerationTools code) { var codeNamespace = code.VsNamespaceSuggestion(); if (!String.IsNullOrEmpty(codeNamespace)) { #> namespace <#=code.EscapeNamespace(codeNamespace)#> { <#+ PushIndent( " " ); } } public void EndNamespace(CodeGenerationTools code) { if (!String.IsNullOrEmpty(code.VsNamespaceSuggestion())) { PopIndent(); #> } <#+ } } public const string TemplateId = "CSharp_DbContext_Types_EF6" ; public class CodeStringGenerator { private readonly CodeGenerationTools _code; private readonly TypeMapper _typeMapper; private readonly MetadataTools _ef; //预设置要导入的包 private string prePackages = "\r\n" + "using DM2.DMP.Common; " + "\r\n" + "using DM2.DMP.WebCommon; " + "\r\n" + "using Data; " + "\r\n" + "using Helper; " + "\r\n" + "using System; " + "\r\n" + "using System.Collections.Generic;" + "\r\n" + "using System.Linq; " + "\r\n" + "using System.Net; " + "\r\n" + "using System.Net.Http; " + "\r\n" + "using System.Web; " + "\r\n" + "using System.Web.Http; " ; public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) { ArgumentNotNull(code, "code" ); ArgumentNotNull(typeMapper, "typeMapper" ); ArgumentNotNull(ef, "ef" ); _code = code; _typeMapper = typeMapper; _ef = ef; } public string Property(EdmProperty edmProperty) { return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}" , Accessibility.ForProperty(edmProperty), _typeMapper.GetTypeName(edmProperty.TypeUsage), _code.Escape(edmProperty), _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); } public string NavigationProperty(NavigationProperty navProp) { var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType()); return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}" , AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)), navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ( "ICollection<" + endType + ">" ) : endType, _code.Escape(navProp), _code.SpaceAfter(Accessibility.ForGetter(navProp)), _code.SpaceAfter(Accessibility.ForSetter(navProp))); } public string AccessibilityAndVirtual( string accessibility) { return accessibility + (accessibility != "private" ? " virtual" : "" ); } public string EntityClassOpening(EntityType entity, string entityName = null ) { return string .Format( CultureInfo.InvariantCulture, "{0} {1}partial class {2}{3}" , Accessibility.ForType(entity), _code.SpaceAfter(_code.AbstractOption(entity)), entityName = (entityName == null ? _code.Escape(entity) : entityName), _code.StringBefore( " : " , "ApiController" )); } public string EnumOpening(SimpleType enumType) { return string .Format( CultureInfo.InvariantCulture, "{0} enum {1} : {2}" , Accessibility.ForType(enumType), _code.Escape(enumType), _code.Escape(_typeMapper.UnderlyingClrType(enumType))); } public void WriteFunctionParameters(EdmFunction edmFunction, Action< string , string , string , string > writeParameter) { var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); foreach ( var parameter in parameters.Where(p => p.NeedsLocalVariable)) { var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null" ; var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")" ; var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))" ; writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); } } public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) { var parameters = _typeMapper.GetParameters(edmFunction); return string .Format( CultureInfo.InvariantCulture, "{0} IQueryable<{1}> {2}({3})" , AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), _code.Escape(edmFunction), string .Join( ", " , parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray())); } public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) { var parameters = _typeMapper.GetParameters(edmFunction); return string .Format( CultureInfo.InvariantCulture, "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});" , _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), edmFunction.NamespaceName, edmFunction.Name, string .Join( ", " , parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), _code.StringBefore( ", " , string .Join( ", " , parameters.Select(p => p.ExecuteParameterName).ToArray()))); } public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) { var parameters = _typeMapper.GetParameters(edmFunction); var returnType = _typeMapper.GetReturnType(edmFunction); var paramList = String.Join( ", " , parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()); if (includeMergeOption) { paramList = _code.StringAfter(paramList, ", " ) + "MergeOption mergeOption" ; } return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2}({3})" , AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">" , _code.Escape(edmFunction), paramList); } public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) { var parameters = _typeMapper.GetParameters(edmFunction); var returnType = _typeMapper.GetReturnType(edmFunction); var callParams = _code.StringBefore( ", " , String.Join( ", " , parameters.Select(p => p.ExecuteParameterName).ToArray())); if (includeMergeOption) { callParams = ", mergeOption" + callParams; } return string .Format( CultureInfo.InvariantCulture, "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});" , returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">" , edmFunction.Name, callParams); } public string DbSet(EntitySet entitySet) { return string .Format( CultureInfo.InvariantCulture, "{0} virtual DbSet<{1}> {2} {{ get; set; }}" , Accessibility.ForReadOnlyProperty(entitySet), _typeMapper.GetTypeName(entitySet.ElementType), _code.Escape(entitySet)); } public string UsingDirectives( bool inHeader, bool includeCollections = true , EntityType entityType = null ) { var directives = inHeader == string .IsNullOrEmpty(_code.VsNamespaceSuggestion()) ? string .Format( CultureInfo.InvariantCulture, "{0}using System;{1}" + "{2}" , inHeader ? Environment.NewLine : "" , includeCollections ? (Environment.NewLine + "using System.Collections.Generic;" ) : "" , inHeader ? "" : Environment.NewLine) : "" ; if (directives == "" ) { return directives; } if (entityType != null ) { prePackages = prePackages.Replace( "{entityType}" ,entityType.Name).Replace( "_" , "" ); } directives+= "\r\n" +prePackages; return directives; } } public class TypeMapper { private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName" ; private readonly System.Collections.IList _errors; private readonly CodeGenerationTools _code; private readonly MetadataTools _ef; public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) { ArgumentNotNull(code, "code" ); ArgumentNotNull(ef, "ef" ); ArgumentNotNull(errors, "errors" ); _code = code; _ef = ef; _errors = errors; } public static string FixNamespaces( string typeName) { return typeName.Replace( "System.Data.Spatial." , "System.Data.Entity.Spatial." ); } public string GetTypeName(TypeUsage typeUsage) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null ); } public string GetTypeName(EdmType edmType) { return GetTypeName(edmType, isNullable: null , modelNamespace: null ); } public string GetTypeName(TypeUsage typeUsage, string modelNamespace) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); } public string GetTypeName(EdmType edmType, string modelNamespace) { return GetTypeName(edmType, isNullable: null , modelNamespace: modelNamespace); } public string GetTypeName(EdmType edmType, bool ? isNullable, string modelNamespace) { if (edmType == null ) { return null ; } var collectionType = edmType as CollectionType; if (collectionType != null ) { return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>" , GetTypeName(collectionType.TypeUsage, modelNamespace)); } var typeName = _code.Escape(edmType.MetadataProperties .Where(p => p.Name == ExternalTypeNameAttributeName) .Select(p => ( string )p.Value) .FirstOrDefault()) ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : _code.Escape(edmType)); if (edmType is StructuralType) { return typeName; } if (edmType is SimpleType) { var clrType = UnderlyingClrType(edmType); if (!IsEnumType(edmType)) { typeName = _code.Escape(clrType); } typeName = FixNamespaces(typeName); return clrType.IsValueType && isNullable == true ? String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>" , typeName) : typeName; } throw new ArgumentException( "edmType" ); } public Type UnderlyingClrType(EdmType edmType) { ArgumentNotNull(edmType, "edmType" ); var primitiveType = edmType as PrimitiveType; if (primitiveType != null ) { return primitiveType.ClrEquivalentType; } if (IsEnumType(edmType)) { return GetEnumUnderlyingType(edmType).ClrEquivalentType; } return typeof ( object ); } public object GetEnumMemberValue(MetadataItem enumMember) { ArgumentNotNull(enumMember, "enumMember" ); var valueProperty = enumMember.GetType().GetProperty( "Value" ); return valueProperty == null ? null : valueProperty.GetValue(enumMember, null ); } public string GetEnumMemberName(MetadataItem enumMember) { ArgumentNotNull(enumMember, "enumMember" ); var nameProperty = enumMember.GetType().GetProperty( "Name" ); return nameProperty == null ? null : ( string )nameProperty.GetValue(enumMember, null ); } public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); var membersProperty = enumType.GetType().GetProperty( "Members" ); return membersProperty != null ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null ) : Enumerable.Empty<MetadataItem>(); } public bool EnumIsFlags(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); var isFlagsProperty = enumType.GetType().GetProperty( "IsFlags" ); return isFlagsProperty != null && ( bool )isFlagsProperty.GetValue(enumType, null ); } public bool IsEnumType(GlobalItem edmType) { ArgumentNotNull(edmType, "edmType" ); return edmType.GetType().Name == "EnumType" ; } public PrimitiveType GetEnumUnderlyingType(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); return (PrimitiveType)enumType.GetType().GetProperty( "UnderlyingType" ).GetValue(enumType, null ); } public string CreateLiteral( object value) { if (value == null || value.GetType() != typeof (TimeSpan)) { return _code.CreateLiteral(value); } return string .Format(CultureInfo.InvariantCulture, "new TimeSpan({0})" , ((TimeSpan)value).Ticks); } public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable< string > types, string sourceFile) { ArgumentNotNull(types, "types" ); ArgumentNotNull(sourceFile, "sourceFile" ); var hash = new HashSet< string >(StringComparer.InvariantCultureIgnoreCase); if (types.Any(item => !hash.Add(item))) { _errors.Add( new CompilerError(sourceFile, -1, -1, "6023" , String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString( "Template_CaseInsensitiveTypeConflict" )))); return false ; } return true ; } public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection) { return GetItemsToGenerate<SimpleType>(itemCollection) .Where(e => IsEnumType(e)); } public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType { return itemCollection .OfType<T>() .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) .OrderBy(i => i.Name); } public IEnumerable< string > GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection) { return itemCollection .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) .Select(g => GetGlobalItemName(g)); } public string GetGlobalItemName(GlobalItem item) { if (item is EdmType) { return ((EdmType)item).Name; } else { return ((EntityContainer)item).Name; } } public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetComplexProperties(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null ); } public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null ); } public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type) { return type.NavigationProperties.Where(np => np.DeclaringType == type); } public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type) { return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); } public FunctionParameter GetReturnParameter(EdmFunction edmFunction) { ArgumentNotNull(edmFunction, "edmFunction" ); var returnParamsProperty = edmFunction.GetType().GetProperty( "ReturnParameters" ); return returnParamsProperty == null ? edmFunction.ReturnParameter : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null )).FirstOrDefault(); } public bool IsComposable(EdmFunction edmFunction) { ArgumentNotNull(edmFunction, "edmFunction" ); var isComposableProperty = edmFunction.GetType().GetProperty( "IsComposableAttribute" ); return isComposableProperty != null && ( bool )isComposableProperty.GetValue(edmFunction, null ); } public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction) { return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); } public TypeUsage GetReturnType(EdmFunction edmFunction) { var returnParam = GetReturnParameter(edmFunction); return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); } public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) { var returnType = GetReturnType(edmFunction); return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; } } public static void ArgumentNotNull<T>(T arg, string name) where T : class { if (arg == null ) { throw new ArgumentNullException(name); } } #> |
生成removecontroller
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 | <#@ template language= "C#" debug= "false" hostspecific= "true" #> <#@ include file= "EF6.Utility.CS.ttinclude" #><#@ output extension= ".cs" #> <# const string inputFile = @"../../MS.Brand.Data/Model.edmx" ; var textTransform = DynamicTextTransformation.Create( this ); var code = new CodeGenerationTools( this ); var ef = new MetadataTools( this ); var typeMapper = new TypeMapper(code, ef, textTransform.Errors); var fileManager = EntityFrameworkTemplateFileManager.Create( this ); var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile); var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile)) { return string .Empty; } var container = itemCollection.OfType<EntityContainer>().FirstOrDefault(); if (container == null ) { return string .Empty; } //----------------------------BEGIN Remove------------------------------------------ WriteHeader(codeStringGenerator, fileManager); foreach ( var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection)) { var tempClassName = "Remove" +entity.Name + "Controller" ; fileManager.StartNewFile(tempClassName+ ".cs" ); BeginNamespace(code); #> <#=codeStringGenerator.UsingDirectives(inHeader: false , entityType:entity)#> <#=codeStringGenerator.EntityClassOpening(entity, tempClassName)#> { <# var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity); var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity); var complexProperties = typeMapper.GetComplexProperties(entity); #> <# var simpleProperties = typeMapper.GetSimpleProperties(entity);; if (simpleProperties.Any()) { #> HttpContextBase Context = null ; /// <summary> /// 删除 <#= entity.Name #> /// </summary> /// <param name="<#= entity.Name.ToLower() #>"><#= entity.Name #>的实例</param> /// <returns></returns> public JsonModelHelper.JsonModel Post(<#= entity.Name #> <#= entity.Name.ToLower() #>) { Context = (HttpContextBase)Request.Properties[ "MS_HttpContext" ]; try { var result = <#= entity.Name #>Helper.Remove(<#= entity.Name.ToLower() #>); if (result == null ) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" }; } if (result.Status != JsonModelHelper.EJsonModel.Success) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" , Data = result.Data }; } return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Success, Information = "成功" }; } catch (Exception ex) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Exception, Information = "异常" , Data = ex }; } } #region 字段 <# foreach ( var edmProperty in simpleProperties) { #> //<#=entity.Name.ToLower()+"."+edmProperty.Name #> <# } } if (complexProperties.Any()) { #> <# foreach ( var complexProperty in complexProperties) { #> <#=codeStringGenerator.Property(complexProperty)#> <# } } var navigationProperties = typeMapper.GetNavigationProperties(entity); if (navigationProperties.Any()) { #> <# foreach ( var navigationProperty in navigationProperties) { if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many) { #> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage" , "CA2227:CollectionPropertiesShouldBeReadOnly" )] <# } #> <#=codeStringGenerator.NavigationProperty(navigationProperty)#> <# } } #> #endregion <#= "}" #> <# EndNamespace(code); } fileManager.Process(); #> //----------------------------END Remove------------------------------------------ <#+ public void WriteHeader(CodeStringGenerator codeStringGenerator, EntityFrameworkTemplateFileManager fileManager) { fileManager.StartHeader(); #> //------------------------------------------------------------------------------ // <auto-generated> // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")#> // // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")#> // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")#> // </auto-generated> //------------------------------------------------------------------------------ <#=codeStringGenerator.UsingDirectives(inHeader: true )#> <#+ fileManager.EndBlock(); } public void BeginNamespace(CodeGenerationTools code) { var codeNamespace = code.VsNamespaceSuggestion(); if (!String.IsNullOrEmpty(codeNamespace)) { #> namespace <#=code.EscapeNamespace(codeNamespace)#> { <#+ PushIndent( " " ); } } public void EndNamespace(CodeGenerationTools code) { if (!String.IsNullOrEmpty(code.VsNamespaceSuggestion())) { PopIndent(); #> } <#+ } } public const string TemplateId = "CSharp_DbContext_Types_EF6" ; public class CodeStringGenerator { private readonly CodeGenerationTools _code; private readonly TypeMapper _typeMapper; private readonly MetadataTools _ef; //预设置要导入的包 private string prePackages = "\r\n" + "using DM2.DMP.Common; " + "\r\n" + "using DM2.DMP.WebCommon; " + "\r\n" + "using Data; " + "\r\n" + "using Helper; " + "\r\n" + "using System; " + "\r\n" + "using System.Collections.Generic;" + "\r\n" + "using System.Linq; " + "\r\n" + "using System.Net; " + "\r\n" + "using System.Net.Http; " + "\r\n" + "using System.Web; " + "\r\n" + "using System.Web.Http; " ; public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) { ArgumentNotNull(code, "code" ); ArgumentNotNull(typeMapper, "typeMapper" ); ArgumentNotNull(ef, "ef" ); _code = code; _typeMapper = typeMapper; _ef = ef; } public string Property(EdmProperty edmProperty) { return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}" , Accessibility.ForProperty(edmProperty), _typeMapper.GetTypeName(edmProperty.TypeUsage), _code.Escape(edmProperty), _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); } public string NavigationProperty(NavigationProperty navProp) { var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType()); return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}" , AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)), navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ( "ICollection<" + endType + ">" ) : endType, _code.Escape(navProp), _code.SpaceAfter(Accessibility.ForGetter(navProp)), _code.SpaceAfter(Accessibility.ForSetter(navProp))); } public string AccessibilityAndVirtual( string accessibility) { return accessibility + (accessibility != "private" ? " virtual" : "" ); } public string EntityClassOpening(EntityType entity, string entityName = null ) { return string .Format( CultureInfo.InvariantCulture, "{0} {1}partial class {2}{3}" , Accessibility.ForType(entity), _code.SpaceAfter(_code.AbstractOption(entity)), entityName = (entityName == null ? _code.Escape(entity) : entityName), _code.StringBefore( " : " , "ApiController" )); } public string EnumOpening(SimpleType enumType) { return string .Format( CultureInfo.InvariantCulture, "{0} enum {1} : {2}" , Accessibility.ForType(enumType), _code.Escape(enumType), _code.Escape(_typeMapper.UnderlyingClrType(enumType))); } public void WriteFunctionParameters(EdmFunction edmFunction, Action< string , string , string , string > writeParameter) { var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); foreach ( var parameter in parameters.Where(p => p.NeedsLocalVariable)) { var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null" ; var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")" ; var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))" ; writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); } } public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) { var parameters = _typeMapper.GetParameters(edmFunction); return string .Format( CultureInfo.InvariantCulture, "{0} IQueryable<{1}> {2}({3})" , AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), _code.Escape(edmFunction), string .Join( ", " , parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray())); } public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) { var parameters = _typeMapper.GetParameters(edmFunction); return string .Format( CultureInfo.InvariantCulture, "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});" , _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), edmFunction.NamespaceName, edmFunction.Name, string .Join( ", " , parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), _code.StringBefore( ", " , string .Join( ", " , parameters.Select(p => p.ExecuteParameterName).ToArray()))); } public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) { var parameters = _typeMapper.GetParameters(edmFunction); var returnType = _typeMapper.GetReturnType(edmFunction); var paramList = String.Join( ", " , parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()); if (includeMergeOption) { paramList = _code.StringAfter(paramList, ", " ) + "MergeOption mergeOption" ; } return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2}({3})" , AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">" , _code.Escape(edmFunction), paramList); } public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) { var parameters = _typeMapper.GetParameters(edmFunction); var returnType = _typeMapper.GetReturnType(edmFunction); var callParams = _code.StringBefore( ", " , String.Join( ", " , parameters.Select(p => p.ExecuteParameterName).ToArray())); if (includeMergeOption) { callParams = ", mergeOption" + callParams; } return string .Format( CultureInfo.InvariantCulture, "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});" , returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">" , edmFunction.Name, callParams); } public string DbSet(EntitySet entitySet) { return string .Format( CultureInfo.InvariantCulture, "{0} virtual DbSet<{1}> {2} {{ get; set; }}" , Accessibility.ForReadOnlyProperty(entitySet), _typeMapper.GetTypeName(entitySet.ElementType), _code.Escape(entitySet)); } public string UsingDirectives( bool inHeader, bool includeCollections = true , EntityType entityType = null ) { var directives = inHeader == string .IsNullOrEmpty(_code.VsNamespaceSuggestion()) ? string .Format( CultureInfo.InvariantCulture, "{0}using System;{1}" + "{2}" , inHeader ? Environment.NewLine : "" , includeCollections ? (Environment.NewLine + "using System.Collections.Generic;" ) : "" , inHeader ? "" : Environment.NewLine) : "" ; if (directives == "" ) { return directives; } if (entityType != null ) { prePackages = prePackages.Replace( "{entityType}" ,entityType.Name).Replace( "_" , "" ); } directives+= "\r\n" +prePackages; return directives; } } public class TypeMapper { private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName" ; private readonly System.Collections.IList _errors; private readonly CodeGenerationTools _code; private readonly MetadataTools _ef; public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) { ArgumentNotNull(code, "code" ); ArgumentNotNull(ef, "ef" ); ArgumentNotNull(errors, "errors" ); _code = code; _ef = ef; _errors = errors; } public static string FixNamespaces( string typeName) { return typeName.Replace( "System.Data.Spatial." , "System.Data.Entity.Spatial." ); } public string GetTypeName(TypeUsage typeUsage) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null ); } public string GetTypeName(EdmType edmType) { return GetTypeName(edmType, isNullable: null , modelNamespace: null ); } public string GetTypeName(TypeUsage typeUsage, string modelNamespace) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); } public string GetTypeName(EdmType edmType, string modelNamespace) { return GetTypeName(edmType, isNullable: null , modelNamespace: modelNamespace); } public string GetTypeName(EdmType edmType, bool ? isNullable, string modelNamespace) { if (edmType == null ) { return null ; } var collectionType = edmType as CollectionType; if (collectionType != null ) { return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>" , GetTypeName(collectionType.TypeUsage, modelNamespace)); } var typeName = _code.Escape(edmType.MetadataProperties .Where(p => p.Name == ExternalTypeNameAttributeName) .Select(p => ( string )p.Value) .FirstOrDefault()) ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : _code.Escape(edmType)); if (edmType is StructuralType) { return typeName; } if (edmType is SimpleType) { var clrType = UnderlyingClrType(edmType); if (!IsEnumType(edmType)) { typeName = _code.Escape(clrType); } typeName = FixNamespaces(typeName); return clrType.IsValueType && isNullable == true ? String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>" , typeName) : typeName; } throw new ArgumentException( "edmType" ); } public Type UnderlyingClrType(EdmType edmType) { ArgumentNotNull(edmType, "edmType" ); var primitiveType = edmType as PrimitiveType; if (primitiveType != null ) { return primitiveType.ClrEquivalentType; } if (IsEnumType(edmType)) { return GetEnumUnderlyingType(edmType).ClrEquivalentType; } return typeof ( object ); } public object GetEnumMemberValue(MetadataItem enumMember) { ArgumentNotNull(enumMember, "enumMember" ); var valueProperty = enumMember.GetType().GetProperty( "Value" ); return valueProperty == null ? null : valueProperty.GetValue(enumMember, null ); } public string GetEnumMemberName(MetadataItem enumMember) { ArgumentNotNull(enumMember, "enumMember" ); var nameProperty = enumMember.GetType().GetProperty( "Name" ); return nameProperty == null ? null : ( string )nameProperty.GetValue(enumMember, null ); } public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); var membersProperty = enumType.GetType().GetProperty( "Members" ); return membersProperty != null ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null ) : Enumerable.Empty<MetadataItem>(); } public bool EnumIsFlags(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); var isFlagsProperty = enumType.GetType().GetProperty( "IsFlags" ); return isFlagsProperty != null && ( bool )isFlagsProperty.GetValue(enumType, null ); } public bool IsEnumType(GlobalItem edmType) { ArgumentNotNull(edmType, "edmType" ); return edmType.GetType().Name == "EnumType" ; } public PrimitiveType GetEnumUnderlyingType(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); return (PrimitiveType)enumType.GetType().GetProperty( "UnderlyingType" ).GetValue(enumType, null ); } public string CreateLiteral( object value) { if (value == null || value.GetType() != typeof (TimeSpan)) { return _code.CreateLiteral(value); } return string .Format(CultureInfo.InvariantCulture, "new TimeSpan({0})" , ((TimeSpan)value).Ticks); } public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable< string > types, string sourceFile) { ArgumentNotNull(types, "types" ); ArgumentNotNull(sourceFile, "sourceFile" ); var hash = new HashSet< string >(StringComparer.InvariantCultureIgnoreCase); if (types.Any(item => !hash.Add(item))) { _errors.Add( new CompilerError(sourceFile, -1, -1, "6023" , String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString( "Template_CaseInsensitiveTypeConflict" )))); return false ; } return true ; } public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection) { return GetItemsToGenerate<SimpleType>(itemCollection) .Where(e => IsEnumType(e)); } public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType { return itemCollection .OfType<T>() .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) .OrderBy(i => i.Name); } public IEnumerable< string > GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection) { return itemCollection .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) .Select(g => GetGlobalItemName(g)); } public string GetGlobalItemName(GlobalItem item) { if (item is EdmType) { return ((EdmType)item).Name; } else { return ((EntityContainer)item).Name; } } public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetComplexProperties(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null ); } public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null ); } public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type) { return type.NavigationProperties.Where(np => np.DeclaringType == type); } public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type) { return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); } public FunctionParameter GetReturnParameter(EdmFunction edmFunction) { ArgumentNotNull(edmFunction, "edmFunction" ); var returnParamsProperty = edmFunction.GetType().GetProperty( "ReturnParameters" ); return returnParamsProperty == null ? edmFunction.ReturnParameter : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null )).FirstOrDefault(); } public bool IsComposable(EdmFunction edmFunction) { ArgumentNotNull(edmFunction, "edmFunction" ); var isComposableProperty = edmFunction.GetType().GetProperty( "IsComposableAttribute" ); return isComposableProperty != null && ( bool )isComposableProperty.GetValue(edmFunction, null ); } public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction) { return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); } public TypeUsage GetReturnType(EdmFunction edmFunction) { var returnParam = GetReturnParameter(edmFunction); return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); } public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) { var returnType = GetReturnType(edmFunction); return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; } } public static void ArgumentNotNull<T>(T arg, string name) where T : class { if (arg == null ) { throw new ArgumentNullException(name); } } #> |
生成findcontrlller
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 | <#@ template language= "C#" debug= "false" hostspecific= "true" #> <#@ include file= "EF6.Utility.CS.ttinclude" #><#@ output extension= ".cs" #> <# const string inputFile = @"../../MS.Brand.Data/Model.edmx" ; var textTransform = DynamicTextTransformation.Create( this ); var code = new CodeGenerationTools( this ); var ef = new MetadataTools( this ); var typeMapper = new TypeMapper(code, ef, textTransform.Errors); var fileManager = EntityFrameworkTemplateFileManager.Create( this ); var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile); var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile)) { return string .Empty; } var container = itemCollection.OfType<EntityContainer>().FirstOrDefault(); if (container == null ) { return string .Empty; } //----------------------------BEGIN ADD------------------------------------------ WriteHeader(codeStringGenerator, fileManager); foreach ( var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection)) { var tempClassName = "Find" +entity.Name + "Controller" ; fileManager.StartNewFile(tempClassName+ ".cs" ); BeginNamespace(code); #> <#=codeStringGenerator.UsingDirectives(inHeader: false , entityType:entity)#> <#=codeStringGenerator.EntityClassOpening(entity, tempClassName)#> { <# var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity); var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity); var complexProperties = typeMapper.GetComplexProperties(entity); #> <# var simpleProperties = typeMapper.GetSimpleProperties(entity);; if (simpleProperties.Any()) { #> HttpContextBase Context = null ; /// <summary> /// 查询 <#= entity.Name #> /// </summary> /// <param name="<#= entity.Name.ToLower() #>"><#= entity.Name #>的实例</param> /// <returns></returns> public JsonModelHelper.JsonModel Get(<#= entity.Name #> <#= entity.Name.ToLower() #>) { Context = (HttpContextBase)Request.Properties[ "MS_HttpContext" ]; try { var list = new List<<#= entity.Name #>>(); var result = <#= entity.Name #>Helper.Find(e => { return true ; }, out list, 20, 1); if (result == null ) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" }; } if (result.Status != JsonModelHelper.EJsonModel.Success) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Fail, Information = "失败" }; } return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Success, Information = "成功" , Data = result.Data }; } catch (Exception ex) { return new JsonModelHelper.JsonModel { Status = JsonModelHelper.EJsonModel.Exception, Information = "异常" , Data = ex }; } } #region 字段 <# foreach ( var edmProperty in simpleProperties) { #> //<#=entity.Name.ToLower()+"."+edmProperty.Name #> <# } } if (complexProperties.Any()) { #> <# foreach ( var complexProperty in complexProperties) { #> <#=codeStringGenerator.Property(complexProperty)#> <# } } var navigationProperties = typeMapper.GetNavigationProperties(entity); if (navigationProperties.Any()) { #> <# foreach ( var navigationProperty in navigationProperties) { if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many) { #> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage" , "CA2227:CollectionPropertiesShouldBeReadOnly" )] <# } #> <#=codeStringGenerator.NavigationProperty(navigationProperty)#> <# } } #> #endregion <#= "}" #> <# EndNamespace(code); } fileManager.Process(); #> //----------------------------END ADD------------------------------------------ <#+ public void WriteHeader(CodeStringGenerator codeStringGenerator, EntityFrameworkTemplateFileManager fileManager) { fileManager.StartHeader(); #> //------------------------------------------------------------------------------ // <auto-generated> // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")#> // // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")#> // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")#> // </auto-generated> //------------------------------------------------------------------------------ <#=codeStringGenerator.UsingDirectives(inHeader: true )#> <#+ fileManager.EndBlock(); } public void BeginNamespace(CodeGenerationTools code) { var codeNamespace = code.VsNamespaceSuggestion(); if (!String.IsNullOrEmpty(codeNamespace)) { #> namespace <#=code.EscapeNamespace(codeNamespace)#> { <#+ PushIndent( " " ); } } public void EndNamespace(CodeGenerationTools code) { if (!String.IsNullOrEmpty(code.VsNamespaceSuggestion())) { PopIndent(); #> } <#+ } } public const string TemplateId = "CSharp_DbContext_Types_EF6" ; public class CodeStringGenerator { private readonly CodeGenerationTools _code; private readonly TypeMapper _typeMapper; private readonly MetadataTools _ef; //预设置要导入的包 private string prePackages = "\r\n" + "using DM2.DMP.Common; " + "\r\n" + "using DM2.DMP.WebCommon; " + "\r\n" + "using Data; " + "\r\n" + "using Helper; " + "\r\n" + "using System; " + "\r\n" + "using System.Collections.Generic;" + "\r\n" + "using System.Linq; " + "\r\n" + "using System.Net; " + "\r\n" + "using System.Net.Http; " + "\r\n" + "using System.Web; " + "\r\n" + "using System.Web.Http; " ; public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) { ArgumentNotNull(code, "code" ); ArgumentNotNull(typeMapper, "typeMapper" ); ArgumentNotNull(ef, "ef" ); _code = code; _typeMapper = typeMapper; _ef = ef; } public string Property(EdmProperty edmProperty) { return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}" , Accessibility.ForProperty(edmProperty), _typeMapper.GetTypeName(edmProperty.TypeUsage), _code.Escape(edmProperty), _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); } public string NavigationProperty(NavigationProperty navProp) { var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType()); return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}" , AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)), navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ( "ICollection<" + endType + ">" ) : endType, _code.Escape(navProp), _code.SpaceAfter(Accessibility.ForGetter(navProp)), _code.SpaceAfter(Accessibility.ForSetter(navProp))); } public string AccessibilityAndVirtual( string accessibility) { return accessibility + (accessibility != "private" ? " virtual" : "" ); } public string EntityClassOpening(EntityType entity, string entityName = null ) { return string .Format( CultureInfo.InvariantCulture, "{0} {1}partial class {2}{3}" , Accessibility.ForType(entity), _code.SpaceAfter(_code.AbstractOption(entity)), entityName = (entityName == null ? _code.Escape(entity) : entityName), _code.StringBefore( " : " , "ApiController" )); } public string EnumOpening(SimpleType enumType) { return string .Format( CultureInfo.InvariantCulture, "{0} enum {1} : {2}" , Accessibility.ForType(enumType), _code.Escape(enumType), _code.Escape(_typeMapper.UnderlyingClrType(enumType))); } public void WriteFunctionParameters(EdmFunction edmFunction, Action< string , string , string , string > writeParameter) { var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); foreach ( var parameter in parameters.Where(p => p.NeedsLocalVariable)) { var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null" ; var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")" ; var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))" ; writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); } } public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) { var parameters = _typeMapper.GetParameters(edmFunction); return string .Format( CultureInfo.InvariantCulture, "{0} IQueryable<{1}> {2}({3})" , AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), _code.Escape(edmFunction), string .Join( ", " , parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray())); } public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) { var parameters = _typeMapper.GetParameters(edmFunction); return string .Format( CultureInfo.InvariantCulture, "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});" , _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), edmFunction.NamespaceName, edmFunction.Name, string .Join( ", " , parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), _code.StringBefore( ", " , string .Join( ", " , parameters.Select(p => p.ExecuteParameterName).ToArray()))); } public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) { var parameters = _typeMapper.GetParameters(edmFunction); var returnType = _typeMapper.GetReturnType(edmFunction); var paramList = String.Join( ", " , parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()); if (includeMergeOption) { paramList = _code.StringAfter(paramList, ", " ) + "MergeOption mergeOption" ; } return string .Format( CultureInfo.InvariantCulture, "{0} {1} {2}({3})" , AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">" , _code.Escape(edmFunction), paramList); } public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) { var parameters = _typeMapper.GetParameters(edmFunction); var returnType = _typeMapper.GetReturnType(edmFunction); var callParams = _code.StringBefore( ", " , String.Join( ", " , parameters.Select(p => p.ExecuteParameterName).ToArray())); if (includeMergeOption) { callParams = ", mergeOption" + callParams; } return string .Format( CultureInfo.InvariantCulture, "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});" , returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">" , edmFunction.Name, callParams); } public string DbSet(EntitySet entitySet) { return string .Format( CultureInfo.InvariantCulture, "{0} virtual DbSet<{1}> {2} {{ get; set; }}" , Accessibility.ForReadOnlyProperty(entitySet), _typeMapper.GetTypeName(entitySet.ElementType), _code.Escape(entitySet)); } public string UsingDirectives( bool inHeader, bool includeCollections = true , EntityType entityType = null ) { var directives = inHeader == string .IsNullOrEmpty(_code.VsNamespaceSuggestion()) ? string .Format( CultureInfo.InvariantCulture, "{0}using System;{1}" + "{2}" , inHeader ? Environment.NewLine : "" , includeCollections ? (Environment.NewLine + "using System.Collections.Generic;" ) : "" , inHeader ? "" : Environment.NewLine) : "" ; if (directives == "" ) { return directives; } if (entityType != null ) { prePackages = prePackages.Replace( "{entityType}" ,entityType.Name).Replace( "_" , "" ); } directives+= "\r\n" +prePackages; return directives; } } public class TypeMapper { private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName" ; private readonly System.Collections.IList _errors; private readonly CodeGenerationTools _code; private readonly MetadataTools _ef; public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) { ArgumentNotNull(code, "code" ); ArgumentNotNull(ef, "ef" ); ArgumentNotNull(errors, "errors" ); _code = code; _ef = ef; _errors = errors; } public static string FixNamespaces( string typeName) { return typeName.Replace( "System.Data.Spatial." , "System.Data.Entity.Spatial." ); } public string GetTypeName(TypeUsage typeUsage) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null ); } public string GetTypeName(EdmType edmType) { return GetTypeName(edmType, isNullable: null , modelNamespace: null ); } public string GetTypeName(TypeUsage typeUsage, string modelNamespace) { return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); } public string GetTypeName(EdmType edmType, string modelNamespace) { return GetTypeName(edmType, isNullable: null , modelNamespace: modelNamespace); } public string GetTypeName(EdmType edmType, bool ? isNullable, string modelNamespace) { if (edmType == null ) { return null ; } var collectionType = edmType as CollectionType; if (collectionType != null ) { return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>" , GetTypeName(collectionType.TypeUsage, modelNamespace)); } var typeName = _code.Escape(edmType.MetadataProperties .Where(p => p.Name == ExternalTypeNameAttributeName) .Select(p => ( string )p.Value) .FirstOrDefault()) ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : _code.Escape(edmType)); if (edmType is StructuralType) { return typeName; } if (edmType is SimpleType) { var clrType = UnderlyingClrType(edmType); if (!IsEnumType(edmType)) { typeName = _code.Escape(clrType); } typeName = FixNamespaces(typeName); return clrType.IsValueType && isNullable == true ? String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>" , typeName) : typeName; } throw new ArgumentException( "edmType" ); } public Type UnderlyingClrType(EdmType edmType) { ArgumentNotNull(edmType, "edmType" ); var primitiveType = edmType as PrimitiveType; if (primitiveType != null ) { return primitiveType.ClrEquivalentType; } if (IsEnumType(edmType)) { return GetEnumUnderlyingType(edmType).ClrEquivalentType; } return typeof ( object ); } public object GetEnumMemberValue(MetadataItem enumMember) { ArgumentNotNull(enumMember, "enumMember" ); var valueProperty = enumMember.GetType().GetProperty( "Value" ); return valueProperty == null ? null : valueProperty.GetValue(enumMember, null ); } public string GetEnumMemberName(MetadataItem enumMember) { ArgumentNotNull(enumMember, "enumMember" ); var nameProperty = enumMember.GetType().GetProperty( "Name" ); return nameProperty == null ? null : ( string )nameProperty.GetValue(enumMember, null ); } public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); var membersProperty = enumType.GetType().GetProperty( "Members" ); return membersProperty != null ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null ) : Enumerable.Empty<MetadataItem>(); } public bool EnumIsFlags(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); var isFlagsProperty = enumType.GetType().GetProperty( "IsFlags" ); return isFlagsProperty != null && ( bool )isFlagsProperty.GetValue(enumType, null ); } public bool IsEnumType(GlobalItem edmType) { ArgumentNotNull(edmType, "edmType" ); return edmType.GetType().Name == "EnumType" ; } public PrimitiveType GetEnumUnderlyingType(EdmType enumType) { ArgumentNotNull(enumType, "enumType" ); return (PrimitiveType)enumType.GetType().GetProperty( "UnderlyingType" ).GetValue(enumType, null ); } public string CreateLiteral( object value) { if (value == null || value.GetType() != typeof (TimeSpan)) { return _code.CreateLiteral(value); } return string .Format(CultureInfo.InvariantCulture, "new TimeSpan({0})" , ((TimeSpan)value).Ticks); } public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable< string > types, string sourceFile) { ArgumentNotNull(types, "types" ); ArgumentNotNull(sourceFile, "sourceFile" ); var hash = new HashSet< string >(StringComparer.InvariantCultureIgnoreCase); if (types.Any(item => !hash.Add(item))) { _errors.Add( new CompilerError(sourceFile, -1, -1, "6023" , String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString( "Template_CaseInsensitiveTypeConflict" )))); return false ; } return true ; } public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection) { return GetItemsToGenerate<SimpleType>(itemCollection) .Where(e => IsEnumType(e)); } public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType { return itemCollection .OfType<T>() .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) .OrderBy(i => i.Name); } public IEnumerable< string > GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection) { return itemCollection .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) .Select(g => GetGlobalItemName(g)); } public string GetGlobalItemName(GlobalItem item) { if (item is EdmType) { return ((EdmType)item).Name; } else { return ((EntityContainer)item).Name; } } public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetComplexProperties(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); } public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null ); } public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type) { return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null ); } public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type) { return type.NavigationProperties.Where(np => np.DeclaringType == type); } public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type) { return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); } public FunctionParameter GetReturnParameter(EdmFunction edmFunction) { ArgumentNotNull(edmFunction, "edmFunction" ); var returnParamsProperty = edmFunction.GetType().GetProperty( "ReturnParameters" ); return returnParamsProperty == null ? edmFunction.ReturnParameter : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null )).FirstOrDefault(); } public bool IsComposable(EdmFunction edmFunction) { ArgumentNotNull(edmFunction, "edmFunction" ); var isComposableProperty = edmFunction.GetType().GetProperty( "IsComposableAttribute" ); return isComposableProperty != null && ( bool )isComposableProperty.GetValue(edmFunction, null ); } public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction) { return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); } public TypeUsage GetReturnType(EdmFunction edmFunction) { var returnParam = GetReturnParameter(edmFunction); return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); } public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) { var returnType = GetReturnType(edmFunction); return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; } } public static void ArgumentNotNull<T>(T arg, string name) where T : class { if (arg == null ) { throw new ArgumentNullException(name); } } #> |
大家根据自己的需要修改即可。怎删改查 节省时间 非常好用
复制到文本里,拓展名改为.tt 使用的时候复制到项目里 ,替换成您本地的xxx.edmx,ctrl+s就会生成,生成完成删掉.tt就可以了
:)
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
2017-03-25 Ubuntu中开启和关闭防火墙-摘自网络
2009-03-25 SqlCommandBuilder 类