├── .gitattributes ├── .github └── issue_template.md ├── .gitignore ├── .nuget ├── NuGet.Config ├── NuGet.exe └── NuGet.targets ├── AutoMapperSamples.sln ├── LICENSE.md ├── README.md ├── Sample01 ├── App.config ├── Config │ ├── Configuration.cs │ ├── InitEF.cs │ └── MyContext.cs ├── Models │ ├── BlogPost.cs │ └── User.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample01.csproj └── packages.config ├── Sample02 ├── AutoMapperConfig │ ├── DateTimeToPersianDateTimeConverter.cs │ ├── StringFromDateTimeTypeConverter.cs │ ├── TestProfile1.cs │ └── TestProfile2.cs ├── Models │ ├── User.cs │ └── UserViewModel.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample02.csproj ├── app.config └── packages.config ├── Sample03 ├── AutoMapperConfig │ ├── IHaveCustomMappings.cs │ ├── PersianExtensions.cs │ └── TestProfile.cs ├── IoCConfig │ ├── AutomapperRegistry.cs │ └── SmObjectFactory.cs ├── Models │ ├── AutoWire │ │ ├── Person.cs │ │ └── PersonViewModel.cs │ ├── HaveCustomMappings │ │ ├── ApplicationUser.cs │ │ └── ApplicationUserViewModel.cs │ ├── User.cs │ └── UserViewModel.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample03.csproj ├── Services │ ├── IUsersService.cs │ └── UsersService.cs ├── app.config └── packages.config ├── Sample04 ├── App.config ├── Config │ ├── Configuration.cs │ ├── InitEF.cs │ └── MyContext.cs ├── Models │ ├── Advertisement.cs │ ├── BaseEntity.cs │ └── User.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample04.csproj └── packages.config ├── Sample05 ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample05.csproj ├── app.config └── packages.config ├── Sample06 ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample06.csproj ├── app.config └── packages.config ├── Sample07 ├── App.config ├── IoCConfig │ ├── AutomapperRegistry.cs │ └── SmObjectFactory.cs ├── MappingProfiles │ ├── AdvertisementsProfile.cs │ └── UsersProfile.cs ├── Models │ ├── Advertisement.cs │ └── User.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample07.csproj ├── Services │ ├── AdoMapper.cs │ ├── AdvertisementsService.cs │ ├── Contracts │ │ ├── IAdvertisementsService.cs │ │ └── IUsersService.cs │ └── UsersService.cs └── packages.config ├── Sample08 ├── App.config ├── Config │ ├── Configuration.cs │ ├── InitEF.cs │ └── MyContext.cs ├── MappingProfiles │ └── StudentsProfile.cs ├── Models │ ├── Student.cs │ └── StudentViewModel.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample08.csproj └── packages.config ├── Sample09 ├── App.config ├── Config │ ├── Configuration.cs │ ├── InitEF.cs │ └── MyContext.cs ├── MappingsConfig │ └── Profiles │ │ ├── CustomerAttributeProfile.cs │ │ ├── CustomerProfile.cs │ │ ├── OrderItemsProfile.cs │ │ └── OrderProfile.cs ├── Models │ ├── Customer.cs │ ├── CustomerAttribute.cs │ ├── Order.cs │ └── OrderItem.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample09.csproj ├── ViewModels │ ├── CustomerAttributeViewModel.cs │ ├── CustomerViewModel.cs │ ├── NumberOfOrderViewModel.cs │ ├── OrderDateViewModel.cs │ ├── OrderItemsViewModel.cs │ ├── OrderShipViewModel.cs │ └── OrderViewModel.cs └── packages.config ├── Sample10 ├── App.config ├── Config │ ├── Configuration.cs │ ├── InitEF.cs │ └── MyContext.cs ├── MappingsConfig │ └── TestProfile.cs ├── Models │ ├── BlogPost.cs │ └── User.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample10.csproj ├── ViewModels │ └── UserViewModel.cs └── packages.config ├── Sample11 ├── App.config ├── Config │ ├── Configuration.cs │ ├── InitEF.cs │ └── MyContext.cs ├── MappingsConfig │ └── TestProfile.cs ├── Models │ ├── Address.cs │ ├── Email.cs │ └── SiteUser.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample11.csproj ├── ViewModels │ └── UserViewModel.cs └── packages.config ├── Sample12 ├── App_Start │ ├── FilterConfig.cs │ ├── RouteConfig.cs │ └── WebApiConfig.cs ├── AutoMapperConfig │ ├── AttributeMapping │ │ ├── AutoMapperExtensions.cs │ │ ├── MappedMetadataProvider.cs │ │ └── MappedValidatorProvider.cs │ ├── Mappings.cs │ └── UsersProfile.cs ├── Content │ ├── Site.css │ ├── bootstrap.css │ └── bootstrap.min.css ├── Controllers │ └── HomeController.cs ├── Global.asax ├── Global.asax.cs ├── Models │ └── UserModel.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample12.csproj ├── Scripts │ ├── _references.js │ ├── bootstrap.js │ ├── bootstrap.min.js │ ├── jquery-1.10.2.intellisense.js │ ├── jquery-1.10.2.js │ ├── jquery-1.10.2.min.js │ ├── jquery-1.10.2.min.map │ ├── jquery.validate-vsdoc.js │ ├── jquery.validate.js │ ├── jquery.validate.min.js │ ├── jquery.validate.unobtrusive.js │ ├── jquery.validate.unobtrusive.min.js │ ├── modernizr-2.6.2.js │ ├── respond.js │ └── respond.min.js ├── ViewModels │ └── UserViewModel.cs ├── Views │ ├── Home │ │ └── Index.cshtml │ ├── Shared │ │ ├── Error.cshtml │ │ └── _Layout.cshtml │ ├── Web.config │ ├── Web.config.bak │ └── _ViewStart.cshtml ├── Web.Debug.config ├── Web.Release.config ├── Web.config ├── Web.config.bak └── packages.config ├── Sample13 ├── AutoMapperConfig │ └── UsersProfile.cs ├── Models │ └── UserModel.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Sample13.csproj ├── ViewModels │ └── UserViewModel.cs ├── app.config └── packages.config └── Sample14 ├── Models ├── Person.cs ├── PersonDto.cs ├── PersonList.cs └── PersonType.cs ├── Properties └── AssemblyInfo.cs ├── Sample14.csproj ├── UnitTests.cs └── packages.config /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/issue_template.md: -------------------------------------------------------------------------------- 1 | # Summary of the issue 2 | 3 | 4 | 5 | ## Environment 6 | 7 | ``` 8 | The in-use version: 9 | Operating system: 10 | IDE: (e.g. Visual Studio 2015) 11 | ``` 12 | 13 | ## Example code/Steps to reproduce: 14 | 15 | ``` 16 | paste your core code 17 | ``` 18 | 19 | ## Output: 20 | 21 | ``` 22 | Exception message: 23 | Full Stack trace: 24 | ``` 25 | 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | [Dd]ebug/ 11 | [Dd]ebugPublic/ 12 | [Rr]elease/ 13 | x64/ 14 | build/ 15 | bld/ 16 | [Bb]in/ 17 | [Oo]bj/ 18 | 19 | # Roslyn cache directories 20 | *.ide/ 21 | 22 | # MSTest test Results 23 | [Tt]est[Rr]esult*/ 24 | [Bb]uild[Ll]og.* 25 | 26 | #NUNIT 27 | *.VisualState.xml 28 | TestResult.xml 29 | 30 | # Build Results of an ATL Project 31 | [Dd]ebugPS/ 32 | [Rr]eleasePS/ 33 | dlldata.c 34 | 35 | *_i.c 36 | *_p.c 37 | *_i.h 38 | *.ilk 39 | *.meta 40 | *.obj 41 | *.pch 42 | *.pdb 43 | *.pgc 44 | *.pgd 45 | *.rsp 46 | *.sbr 47 | *.tlb 48 | *.tli 49 | *.tlh 50 | *.tmp 51 | *.tmp_proj 52 | *.log 53 | *.vspscc 54 | *.vssscc 55 | .builds 56 | *.pidb 57 | *.svclog 58 | *.scc 59 | 60 | # Chutzpah Test files 61 | _Chutzpah* 62 | 63 | # Visual C++ cache files 64 | ipch/ 65 | *.aps 66 | *.ncb 67 | *.opensdf 68 | *.sdf 69 | *.cachefile 70 | 71 | # Visual Studio profiler 72 | *.psess 73 | *.vsp 74 | *.vspx 75 | 76 | # TFS 2012 Local Workspace 77 | $tf/ 78 | 79 | # Guidance Automation Toolkit 80 | *.gpState 81 | 82 | # ReSharper is a .NET coding add-in 83 | _ReSharper*/ 84 | *.[Rr]e[Ss]harper 85 | *.DotSettings.user 86 | 87 | # JustCode is a .NET coding addin-in 88 | .JustCode 89 | 90 | # TeamCity is a build add-in 91 | _TeamCity* 92 | 93 | # DotCover is a Code Coverage Tool 94 | *.dotCover 95 | 96 | # NCrunch 97 | _NCrunch_* 98 | .*crunch*.local.xml 99 | 100 | # MightyMoose 101 | *.mm.* 102 | AutoTest.Net/ 103 | 104 | # Web workbench (sass) 105 | .sass-cache/ 106 | 107 | # Installshield output folder 108 | [Ee]xpress/ 109 | 110 | # DocProject is a documentation generator add-in 111 | DocProject/buildhelp/ 112 | DocProject/Help/*.HxT 113 | DocProject/Help/*.HxC 114 | DocProject/Help/*.hhc 115 | DocProject/Help/*.hhk 116 | DocProject/Help/*.hhp 117 | DocProject/Help/Html2 118 | DocProject/Help/html 119 | 120 | # Click-Once directory 121 | publish/ 122 | 123 | # Publish Web Output 124 | *.[Pp]ublish.xml 125 | *.azurePubxml 126 | ## TODO: Comment the next line if you want to checkin your 127 | ## web deploy settings but do note that will include unencrypted 128 | ## passwords 129 | #*.pubxml 130 | 131 | # NuGet Packages Directory 132 | packages/* 133 | ## TODO: If the tool you use requires repositories.config 134 | ## uncomment the next line 135 | #!packages/repositories.config 136 | 137 | # Enable "build/" folder in the NuGet Packages folder since 138 | # NuGet packages use it for MSBuild targets. 139 | # This line needs to be after the ignore of the build folder 140 | # (and the packages folder if the line above has been uncommented) 141 | !packages/build/ 142 | 143 | # Windows Azure Build Output 144 | csx/ 145 | *.build.csdef 146 | 147 | # Windows Store app package directory 148 | AppPackages/ 149 | 150 | # Others 151 | sql/ 152 | *.Cache 153 | ClientBin/ 154 | [Ss]tyle[Cc]op.* 155 | ~$* 156 | *~ 157 | *.dbmdl 158 | *.dbproj.schemaview 159 | *.pfx 160 | *.publishsettings 161 | node_modules/ 162 | 163 | # RIA/Silverlight projects 164 | Generated_Code/ 165 | 166 | # Backup & report files from converting an old project file 167 | # to a newer Visual Studio version. Backup files are not needed, 168 | # because we have git ;-) 169 | _UpgradeReport_Files/ 170 | Backup*/ 171 | UpgradeLog*.XML 172 | UpgradeLog*.htm 173 | 174 | # SQL Server files 175 | *.mdf 176 | *.ldf 177 | 178 | # Business Intelligence projects 179 | *.rdl.data 180 | *.bim.layout 181 | *.bim_*.settings 182 | 183 | # Microsoft Fakes 184 | FakesAssemblies/ 185 | 186 | # LightSwitch generated files 187 | GeneratedArtifacts/ 188 | _Pvt_Extensions/ 189 | ModelManifest.xml 190 | *.scgdat 191 | /.vs/config 192 | *.dat 193 | -------------------------------------------------------------------------------- /.nuget/NuGet.Config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.nuget/NuGet.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VahidN/AutoMapperSamples/cd72c222def6b979e2ba1fa6f60bcafc235513cb/.nuget/NuGet.exe -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | AutoMapper Samples 2 | ======= 3 | Using AutoMapper with Entity Framework. -------------------------------------------------------------------------------- /Sample01/App.config: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Sample01/Config/Configuration.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity.Migrations; 2 | using System.Linq; 3 | using Sample01.Models; 4 | 5 | namespace Sample01.Config 6 | { 7 | public class Configuration : DbMigrationsConfiguration 8 | { 9 | public Configuration() 10 | { 11 | AutomaticMigrationsEnabled = true; 12 | AutomaticMigrationDataLossAllowed = true; 13 | } 14 | 15 | protected override void Seed(MyContext context) 16 | { 17 | if (context.Users.Any()) 18 | { 19 | return; 20 | } 21 | 22 | var user1 = context.Users.Add(new User 23 | { 24 | Name = "Test 1", 25 | Age = 25 26 | }); 27 | 28 | var user2 = context.Users.Add(new User 29 | { 30 | Name = "Test 2", 31 | Age = 35 32 | }); 33 | 34 | context.BlogPosts.Add(new BlogPost 35 | { 36 | Title = "Title 1", 37 | Content = "Content 1", 38 | User = user1 39 | }); 40 | 41 | context.BlogPosts.Add(new BlogPost 42 | { 43 | Title = "Title 11", 44 | Content = "Content 11", 45 | User = user1 46 | }); 47 | 48 | context.BlogPosts.Add(new BlogPost 49 | { 50 | Title = "Title 2", 51 | Content = "Content 2", 52 | User = user2 53 | }); 54 | 55 | base.Seed(context); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /Sample01/Config/InitEF.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity; 2 | 3 | namespace Sample01.Config 4 | { 5 | public static class InitEF 6 | { 7 | public static void StartDb() 8 | { 9 | Database.SetInitializer(new MigrateDatabaseToLatestVersion()); 10 | using (var context = new MyContext()) 11 | { 12 | context.Database.Initialize(force: true); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Sample01/Config/MyContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Entity; 3 | using Sample01.Models; 4 | 5 | namespace Sample01.Config 6 | { 7 | public class MyContext : DbContext 8 | { 9 | public DbSet Users { get; set; } 10 | public DbSet BlogPosts { get; set; } 11 | 12 | public MyContext() 13 | : base("Connection1") 14 | { 15 | this.Database.Log = sql => Console.Write(sql); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Sample01/Models/BlogPost.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | 3 | namespace Sample01.Models 4 | { 5 | public class BlogPost 6 | { 7 | public int Id { get; set; } 8 | public string Title { get; set; } 9 | public string Content { get; set; } 10 | 11 | [ForeignKey("UserId")] 12 | public virtual User User { get; set; } 13 | public int UserId { get; set; } 14 | } 15 | } -------------------------------------------------------------------------------- /Sample01/Models/User.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Sample01.Models 4 | { 5 | public class User 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } 9 | public int Age { get; set; } 10 | 11 | public virtual ICollection BlogPosts { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /Sample01/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data.Entity; 4 | using System.Linq; 5 | using AutoMapper; 6 | using AutoMapper.QueryableExtensions; 7 | using Sample01.Config; 8 | using Sample01.Models; 9 | 10 | namespace Sample01 11 | { 12 | public class UserViewModel 13 | { 14 | public int Id { set; get; } 15 | public string Name { set; get; } 16 | 17 | public ICollection BlogPosts { get; set; } 18 | } 19 | 20 | public class TestProfile : Profile 21 | { 22 | public TestProfile() 23 | { 24 | this.CreateMap(); 25 | } 26 | } 27 | 28 | class Program 29 | { 30 | static void Main(string[] args) 31 | { 32 | InitEF.StartDb(); 33 | 34 | var mapperConfiguration = new MapperConfiguration(cfg => // In Application_Start() 35 | { 36 | cfg.AddProfile(); 37 | }); 38 | mapperConfiguration.AssertConfigurationIsValid(); 39 | var mapper = mapperConfiguration.CreateMapper(); 40 | 41 | eagerLoadingAutoMapper(mapper); 42 | eagerLoadingEF(mapper); 43 | incorrectLazyLoading(mapper); 44 | } 45 | 46 | private static void incorrectLazyLoading(IMapper mapper) 47 | { 48 | Console.WriteLine("\nincorrectLazyLoading"); 49 | 50 | using (var context = new MyContext()) 51 | { 52 | var user1 = context.Users.FirstOrDefault(); 53 | if (user1 != null) 54 | { 55 | var uiUser = new UserViewModel(); 56 | mapper.Map(source: user1, destination: uiUser); 57 | 58 | Console.WriteLine(uiUser.Name); 59 | foreach (var post in uiUser.BlogPosts) 60 | { 61 | Console.WriteLine(post.Title); 62 | } 63 | } 64 | } 65 | } 66 | 67 | private static void eagerLoadingAutoMapper(IMapper mapper) 68 | { 69 | Console.WriteLine("\neagerLoadingAutoMapper"); 70 | 71 | using (var context = new MyContext()) 72 | { 73 | var uiUser = context.Users.ProjectTo(mapper.ConfigurationProvider) 74 | .FirstOrDefault(); 75 | if (uiUser != null) 76 | { 77 | Console.WriteLine(uiUser.Name); 78 | foreach (var post in uiUser.BlogPosts) 79 | { 80 | Console.WriteLine(post.Title); 81 | } 82 | } 83 | } 84 | } 85 | 86 | private static void eagerLoadingEF(IMapper mapper) 87 | { 88 | Console.WriteLine("\neagerLoadingEF"); 89 | 90 | using (var context = new MyContext()) 91 | { 92 | var user1 = context.Users.Include(user => user.BlogPosts) 93 | .FirstOrDefault(); 94 | if (user1 != null) 95 | { 96 | var uiUser = new UserViewModel(); 97 | mapper.Map(source: user1, destination: uiUser); 98 | 99 | Console.WriteLine(uiUser.Name); 100 | foreach (var post in uiUser.BlogPosts) 101 | { 102 | Console.WriteLine(post.Title); 103 | } 104 | } 105 | } 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /Sample01/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample01")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample01")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("703ffec5-8254-49d0-88c1-8f21946965d9")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample01/Sample01.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {A202C760-F2A7-4E0E-880C-00DC5F0AA03B} 8 | Exe 9 | Properties 10 | Sample01 11 | Sample01 12 | v4.5 13 | 512 14 | ..\ 15 | true 16 | a6389389 17 | 18 | 19 | 20 | AnyCPU 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | false 29 | 30 | 31 | AnyCPU 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE 36 | prompt 37 | 4 38 | false 39 | 40 | 41 | 42 | ..\packages\AutoMapper.6.0.2\lib\net45\AutoMapper.dll 43 | True 44 | 45 | 46 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 47 | True 48 | 49 | 50 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 51 | True 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | Designer 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 82 | 83 | 84 | 85 | 86 | 87 | 94 | -------------------------------------------------------------------------------- /Sample01/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Sample02/AutoMapperConfig/DateTimeToPersianDateTimeConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using AutoMapper; 4 | 5 | namespace Sample02.AutoMapperConfig 6 | { 7 | public class DateTimeToPersianDateTimeConverter : ITypeConverter 8 | { 9 | private readonly bool _includeHourMinute; 10 | private readonly string _separator; 11 | 12 | public DateTimeToPersianDateTimeConverter(string separator = "/", bool includeHourMinute = true) 13 | { 14 | _separator = separator; 15 | _includeHourMinute = includeHourMinute; 16 | } 17 | 18 | public string Convert(DateTime source, string destination, ResolutionContext context) 19 | { 20 | return toShamsiDateTime(source); 21 | } 22 | 23 | private string toShamsiDateTime(DateTime info) 24 | { 25 | var year = info.Year; 26 | var month = info.Month; 27 | var day = info.Day; 28 | var persianCalendar = new PersianCalendar(); 29 | var pYear = persianCalendar.GetYear(new DateTime(year, month, day, new GregorianCalendar())); 30 | var pMonth = persianCalendar.GetMonth(new DateTime(year, month, day, new GregorianCalendar())); 31 | var pDay = persianCalendar.GetDayOfMonth(new DateTime(year, month, day, new GregorianCalendar())); 32 | return _includeHourMinute ? 33 | string.Format("{0}{1}{2}{1}{3} {4}:{5}", pYear, _separator, pMonth.ToString("00", CultureInfo.InvariantCulture), pDay.ToString("00", CultureInfo.InvariantCulture), info.Hour.ToString("00"), info.Minute.ToString("00")) 34 | : string.Format("{0}{1}{2}{1}{3}", pYear, _separator, pMonth.ToString("00", CultureInfo.InvariantCulture), pDay.ToString("00", CultureInfo.InvariantCulture)); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Sample02/AutoMapperConfig/StringFromDateTimeTypeConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using AutoMapper; 4 | 5 | namespace Sample02.AutoMapperConfig 6 | { 7 | public class StringFromDateTimeTypeConverter : ITypeConverter 8 | { 9 | public string Convert(DateTime source, string destination, ResolutionContext context) 10 | { 11 | return source.ToString("dd/mm/yyyy", CultureInfo.InvariantCulture); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Sample02/AutoMapperConfig/TestProfile1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using AutoMapper; 3 | using Sample02.Models; 4 | 5 | namespace Sample02.AutoMapperConfig 6 | { 7 | public class TestProfile1 : Profile 8 | { 9 | public TestProfile1() 10 | { 11 | // اين تنظيم سراسري هست و به تمام خواص زماني اعمال مي‌شود 12 | this.CreateMap().ConvertUsing(new DateTimeToPersianDateTimeConverter()); 13 | 14 | this.CreateMap(); 15 | 16 | // اين تنظيم سفارشي‌تر است 17 | /*this.CreateMap() 18 | .ForMember(userViewModel => userViewModel.RegistrationDate, 19 | opt => opt.ResolveUsing(src => 20 | { 21 | var dt = src.RegistrationDate; 22 | return dt.ToShortDateString(); 23 | }));*/ 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Sample02/AutoMapperConfig/TestProfile2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using AutoMapper; 3 | using Sample02.Models; 4 | 5 | namespace Sample02.AutoMapperConfig 6 | { 7 | public class TestProfile2 : Profile 8 | { 9 | public TestProfile2() 10 | { 11 | // type maps are still global. 12 | // اين تنظيم سراسري هست و به تمام خواص زماني اعمال مي‌شود 13 | this.CreateMap().ConvertUsing(new StringFromDateTimeTypeConverter()); 14 | this.CreateMap(); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Sample02/Models/User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Sample02.Models 4 | { 5 | public class User 6 | { 7 | public int Id { set; get; } 8 | public string Name { set; get; } 9 | public DateTime RegistrationDate { set; get; } 10 | } 11 | } -------------------------------------------------------------------------------- /Sample02/Models/UserViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample02.Models 2 | { 3 | public class UserViewModel 4 | { 5 | public int Id { set; get; } 6 | public string Name { set; get; } 7 | public string RegistrationDate { set; get; } 8 | } 9 | } -------------------------------------------------------------------------------- /Sample02/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using AutoMapper; 3 | using Sample02.AutoMapperConfig; 4 | using Sample02.Models; 5 | 6 | namespace Sample02 7 | { 8 | class Program 9 | { 10 | static void Main(string[] args) 11 | { 12 | var dbUser1 = new User 13 | { 14 | Id = 1, 15 | Name = "Test", 16 | RegistrationDate = DateTime.Now.AddDays(-10) 17 | }; 18 | 19 | var uiUser = new UserViewModel(); 20 | 21 | usingLocalConfig(dbUser1, uiUser); 22 | } 23 | 24 | /// 25 | /// AutoMapper 4.2+ uses non-static API. So its config is always local and specific. 26 | /// 27 | private static void usingLocalConfig(User dbUser1, UserViewModel uiUser) 28 | { 29 | var config = new MapperConfiguration(cfg => // In Application_Start() 30 | { 31 | cfg.AddProfile(); 32 | cfg.AddProfile(); 33 | }); 34 | config.AssertConfigurationIsValid(); 35 | 36 | var mapper = config.CreateMapper(); 37 | mapper.Map(source: dbUser1, destination: uiUser); 38 | 39 | Console.WriteLine("RegistrationDate: {0}", uiUser.RegistrationDate); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /Sample02/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample02")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample02")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("06753c09-bc53-4f5c-a51b-343ea1903b9f")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample02/Sample02.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {A9949F58-AAA4-4F3F-A6FC-40164FECEFC1} 8 | Exe 9 | Properties 10 | Sample02 11 | Sample02 12 | v4.5 13 | 512 14 | ..\ 15 | true 16 | 8272ccac 17 | 18 | 19 | 20 | AnyCPU 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | false 29 | 30 | 31 | AnyCPU 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE 36 | prompt 37 | 4 38 | false 39 | 40 | 41 | 42 | ..\packages\AutoMapper.6.0.2\lib\net45\AutoMapper.dll 43 | True 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 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 72 | 73 | 74 | 75 | 76 | 77 | 84 | -------------------------------------------------------------------------------- /Sample02/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Sample02/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Sample03/AutoMapperConfig/IHaveCustomMappings.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace Sample03.AutoMapperConfig 4 | { 5 | public interface IHaveCustomMappings 6 | { 7 | void CreateMappings(IMapperConfigurationExpression configuration); 8 | } 9 | } -------------------------------------------------------------------------------- /Sample03/AutoMapperConfig/PersianExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | 4 | namespace Sample03.AutoMapperConfig 5 | { 6 | public static class PersianExtensions 7 | { 8 | public static string ToShamsiDateTime(this DateTime info) 9 | { 10 | var year = info.Year; 11 | var month = info.Month; 12 | var day = info.Day; 13 | var persianCalendar = new PersianCalendar(); 14 | var pYear = persianCalendar.GetYear(new DateTime(year, month, day, new GregorianCalendar())); 15 | var pMonth = persianCalendar.GetMonth(new DateTime(year, month, day, new GregorianCalendar())); 16 | var pDay = persianCalendar.GetDayOfMonth(new DateTime(year, month, day, new GregorianCalendar())); 17 | return string.Format("{0}{1}{2}{1}{3}", pYear, "/", pMonth.ToString("00", CultureInfo.InvariantCulture), pDay.ToString("00", CultureInfo.InvariantCulture)); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Sample03/AutoMapperConfig/TestProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Sample03.Models; 3 | 4 | namespace Sample03.AutoMapperConfig 5 | { 6 | public class TestProfile : Profile 7 | { 8 | public TestProfile() 9 | { 10 | this.CreateMap() 11 | .ProjectUsing(src => new UserViewModel 12 | { 13 | Id = src.Id, 14 | Name = src.Name, 15 | RegistrationDate = src.RegistrationDate.ToShamsiDateTime() 16 | }); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Sample03/IoCConfig/AutomapperRegistry.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using AutoMapper; 3 | using Sample03.AutoMapperConfig; 4 | using StructureMap; 5 | 6 | namespace Sample03.IoCConfig 7 | { 8 | public class AutoMapperRegistry : Registry 9 | { 10 | public AutoMapperRegistry() 11 | { 12 | this.Scan(scan => 13 | { 14 | scan.TheCallingAssembly(); 15 | //scan.AssemblyContainingType(); // for other asms, if any. 16 | scan.WithDefaultConventions(); 17 | 18 | scan.AddAllTypesOf().NameBy(item => item.FullName); 19 | scan.AddAllTypesOf().NameBy(item => item.FullName); 20 | }); 21 | 22 | this.For().Singleton().Use("MapperConfig", ctx => 23 | { 24 | var config = new MapperConfiguration(cfg => 25 | { 26 | cfg.CreateMissingTypeMaps = true; // It will connect `Person` & `PersonViewModel` automatically. 27 | addAllCustomAutoMapperProfiles(ctx, cfg); 28 | addAllIHaveCustomMappings(ctx, cfg); 29 | }); 30 | config.AssertConfigurationIsValid(); 31 | 32 | return config; 33 | }); 34 | 35 | this.For().Singleton().Use(ctx => ctx.GetInstance().CreateMapper(ctx.GetInstance)); 36 | } 37 | 38 | private static void addAllCustomAutoMapperProfiles(IContext ctx, IMapperConfigurationExpression cfg) 39 | { 40 | var profiles = ctx.GetAllInstances().ToList(); 41 | foreach (var profile in profiles) 42 | { 43 | cfg.AddProfile(profile); 44 | } 45 | } 46 | 47 | private void addAllIHaveCustomMappings(IContext ctx, IMapperConfigurationExpression cfg) 48 | { 49 | var profiles = ctx.GetAllInstances().ToList(); 50 | foreach (var profile in profiles) 51 | { 52 | profile.CreateMappings(cfg); 53 | } 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /Sample03/IoCConfig/SmObjectFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using StructureMap; 4 | 5 | namespace Sample03.IoCConfig 6 | { 7 | public static class SmObjectFactory 8 | { 9 | private static readonly Lazy _containerBuilder = 10 | new Lazy(defaultContainer, LazyThreadSafetyMode.ExecutionAndPublication); 11 | 12 | public static IContainer Container 13 | { 14 | get { return _containerBuilder.Value; } 15 | } 16 | 17 | private static Container defaultContainer() 18 | { 19 | var container = new Container(cfg => 20 | { 21 | cfg.AddRegistry(); 22 | cfg.Scan(scan => 23 | { 24 | scan.TheCallingAssembly(); 25 | //scan.AssemblyContainingType(); // for other asms, if any. 26 | scan.WithDefaultConventions(); 27 | }); 28 | }); 29 | 30 | return container; 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Sample03/Models/AutoWire/Person.cs: -------------------------------------------------------------------------------- 1 | namespace Sample03.Models.AutoWire 2 | { 3 | public class Person 4 | { 5 | public string Name { get; set; } 6 | public string LastName { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Sample03/Models/AutoWire/PersonViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample03.Models.AutoWire 2 | { 3 | public class PersonViewModel 4 | { 5 | public string Name { get; set; } 6 | public string LastName { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Sample03/Models/HaveCustomMappings/ApplicationUser.cs: -------------------------------------------------------------------------------- 1 | namespace Sample03.Models.HaveCustomMappings 2 | { 3 | public class ApplicationUser 4 | { 5 | public string Name { get; set; } 6 | public string LastName { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Sample03/Models/HaveCustomMappings/ApplicationUserViewModel.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Sample03.AutoMapperConfig; 3 | 4 | namespace Sample03.Models.HaveCustomMappings 5 | { 6 | public class ApplicationUserViewModel : IHaveCustomMappings 7 | { 8 | public string UserName { get; set; } 9 | public string LastName { get; set; } 10 | 11 | public void CreateMappings(IMapperConfigurationExpression configuration) 12 | { 13 | configuration.CreateMap() 14 | .ForMember(viewModel => viewModel.UserName, 15 | opt => opt.MapFrom(applicationUser => applicationUser.Name)); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Sample03/Models/User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Sample03.Models 4 | { 5 | public class User 6 | { 7 | public int Id { set; get; } 8 | public string Name { set; get; } 9 | public DateTime RegistrationDate { set; get; } 10 | } 11 | } -------------------------------------------------------------------------------- /Sample03/Models/UserViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample03.Models 2 | { 3 | public class UserViewModel 4 | { 5 | public int Id { set; get; } 6 | public string Name { set; get; } 7 | public string RegistrationDate { set; get; } 8 | } 9 | } -------------------------------------------------------------------------------- /Sample03/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Sample03.IoCConfig; 3 | using Sample03.Services; 4 | 5 | namespace Sample03 6 | { 7 | class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | var usersService = SmObjectFactory.Container.GetInstance(); 12 | /*var user1 = usersService.GetName(id: 1); 13 | Console.WriteLine("{0}", user1.RegistrationDate);*/ 14 | 15 | var users = usersService.GetUsersList(); 16 | foreach (var user in users) 17 | { 18 | Console.WriteLine("{0} - {1}", user.Name, user.RegistrationDate); 19 | } 20 | 21 | var people = usersService.GetPeopleList(); 22 | foreach (var person in people) 23 | { 24 | Console.WriteLine("{0} - {1}", person.Name, person.LastName); 25 | } 26 | 27 | var appUsers = usersService.GetApplicationUsersList(); 28 | foreach (var user in appUsers) 29 | { 30 | Console.WriteLine("{0} - {1}", user.UserName, user.LastName); 31 | } 32 | 33 | Console.WriteLine("\nPress a key..."); 34 | Console.ReadKey(); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Sample03/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample03")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample03")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("9e1611be-6bee-4be4-aaff-7e6260c14cef")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample03/Services/IUsersService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Sample03.Models; 3 | using Sample03.Models.AutoWire; 4 | using Sample03.Models.HaveCustomMappings; 5 | 6 | namespace Sample03.Services 7 | { 8 | public interface IUsersService 9 | { 10 | UserViewModel GetName(int id); 11 | IList GetUsersList(); 12 | IList GetPeopleList(); 13 | IList GetApplicationUsersList(); 14 | } 15 | } -------------------------------------------------------------------------------- /Sample03/Services/UsersService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using AutoMapper; 5 | using AutoMapper.QueryableExtensions; 6 | using Sample03.Models; 7 | using Sample03.Models.AutoWire; 8 | using Sample03.Models.HaveCustomMappings; 9 | 10 | namespace Sample03.Services 11 | { 12 | public class UsersService : IUsersService 13 | { 14 | private readonly IMapper _mapper; 15 | 16 | public UsersService(IMapper mapper) 17 | { 18 | _mapper = mapper; 19 | } 20 | 21 | public UserViewModel GetName(int id) 22 | { 23 | var dbUser1 = new User 24 | { 25 | Id = 1, 26 | Name = "Test", 27 | RegistrationDate = DateTime.Now.AddDays(-10) 28 | }; 29 | 30 | var uiUser = new UserViewModel(); 31 | _mapper.Map(source: dbUser1, destination: uiUser); 32 | return uiUser; 33 | } 34 | 35 | public IList GetUsersList() 36 | { 37 | var users = new List(); 38 | for (var i = 0; i < 100; i++) 39 | { 40 | users.Add(new User 41 | { 42 | Id = i + 1, 43 | Name = string.Format("Test {0}", i), 44 | RegistrationDate = DateTime.Now.AddDays(-10) 45 | }); 46 | } 47 | 48 | return users.AsQueryable() 49 | .ProjectTo(parameters: null, configuration: _mapper.ConfigurationProvider) 50 | .ToList(); 51 | } 52 | 53 | public IList GetPeopleList() 54 | { 55 | var users = new List(); 56 | for (var i = 0; i < 100; i++) 57 | { 58 | users.Add(new Person 59 | { 60 | Name = string.Format("FName {0}", i), 61 | LastName = string.Format("LName {0}", i) 62 | }); 63 | } 64 | 65 | return users.AsQueryable() 66 | .ProjectTo(parameters: null, configuration: _mapper.ConfigurationProvider) 67 | .ToList(); 68 | } 69 | 70 | public IList GetApplicationUsersList() 71 | { 72 | var users = new List(); 73 | for (var i = 0; i < 100; i++) 74 | { 75 | users.Add(new ApplicationUser 76 | { 77 | Name = string.Format("FName {0}", i), 78 | LastName = string.Format("LName {0}", i) 79 | }); 80 | } 81 | 82 | return users.AsQueryable() 83 | .ProjectTo(parameters: null, configuration: _mapper.ConfigurationProvider) 84 | .ToList(); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Sample03/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Sample03/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sample04/App.config: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Sample04/Config/Configuration.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity.Migrations; 2 | using System.Linq; 3 | using Sample04.Models; 4 | 5 | namespace Sample04.Config 6 | { 7 | public class Configuration : DbMigrationsConfiguration 8 | { 9 | public Configuration() 10 | { 11 | AutomaticMigrationsEnabled = true; 12 | AutomaticMigrationDataLossAllowed = true; 13 | } 14 | 15 | protected override void Seed(MyContext context) 16 | { 17 | if (context.Advertisements.Any()) 18 | { 19 | return; 20 | } 21 | 22 | var user1 = context.Users.Add(new User 23 | { 24 | Name = "Test 1" 25 | }); 26 | 27 | 28 | context.Users.Add(new User 29 | { 30 | Name = "Test 2" 31 | }); 32 | 33 | context.Advertisements.Add(new Advertisement 34 | { 35 | Title = "Ad 1", 36 | Description = "bla bla ......... 1", 37 | User = user1 38 | }); 39 | 40 | context.Advertisements.Add(new Advertisement 41 | { 42 | Title = "Ad 2", 43 | Description = "bla bla ......... 2", 44 | User = user1 45 | }); 46 | 47 | base.Seed(context); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /Sample04/Config/InitEF.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity; 2 | 3 | namespace Sample04.Config 4 | { 5 | public static class InitEF 6 | { 7 | public static void StartDb() 8 | { 9 | Database.SetInitializer(new MigrateDatabaseToLatestVersion()); 10 | using (var context = new MyContext()) 11 | { 12 | context.Database.Initialize(force: true); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Sample04/Config/MyContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Entity; 3 | using Sample04.Models; 4 | 5 | namespace Sample04.Config 6 | { 7 | public class MyContext : DbContext 8 | { 9 | public DbSet Advertisements { get; set; } 10 | public DbSet Users { get; set; } 11 | 12 | public MyContext() 13 | : base("Connection1") 14 | { 15 | this.Database.Log = sql => Console.Write(sql); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Sample04/Models/Advertisement.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | 3 | namespace Sample04.Models 4 | { 5 | public class Advertisement : BaseEntity 6 | { 7 | public string Title { get; set; } 8 | public string Description { get; set; } 9 | 10 | [ForeignKey("UserId")] 11 | public virtual User User { get; set; } 12 | public int UserId { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /Sample04/Models/BaseEntity.cs: -------------------------------------------------------------------------------- 1 | namespace Sample04.Models 2 | { 3 | public abstract class BaseEntity 4 | { 5 | public int Id { set; get; } 6 | } 7 | } -------------------------------------------------------------------------------- /Sample04/Models/User.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Sample04.Models 4 | { 5 | public class User : BaseEntity 6 | { 7 | public string Name { set; get; } 8 | 9 | public virtual ICollection Advertisements { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /Sample04/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using AutoMapper; 5 | using Sample04.Config; 6 | using Sample04.Models; 7 | using System.Data.Entity; 8 | 9 | namespace Sample04 10 | { 11 | public class AdvertisementViewModel 12 | { 13 | public int Id { get; set; } 14 | public string Title { get; set; } 15 | public int UserId { get; set; } 16 | } 17 | 18 | public class UserViewModel 19 | { 20 | public int Id { set; get; } 21 | public string Name { set; get; } 22 | public List Advertisements { get; set; } 23 | } 24 | 25 | public class TestProfile : Profile 26 | { 27 | public TestProfile() 28 | { 29 | this.CreateMap() 30 | .ForMember(user => user.Advertisements, opt => opt.Ignore()); 31 | 32 | this.CreateMap(); 33 | 34 | this.CreateMap() 35 | .ForMember(advertisement => advertisement.Description, opt => opt.Ignore()) 36 | .ForMember(advertisement => advertisement.User, opt => opt.Ignore()); 37 | } 38 | } 39 | 40 | class Program 41 | { 42 | static void Main(string[] args) 43 | { 44 | InitEF.StartDb(); 45 | 46 | var config = new MapperConfiguration(cfg => // In Application_Start() 47 | { 48 | cfg.AddProfile(); 49 | }); 50 | config.AssertConfigurationIsValid(); 51 | 52 | var mapper = config.CreateMapper(); 53 | 54 | updateCollection(mapper); 55 | mappToCollection(mapper); 56 | } 57 | 58 | private static void updateCollection(IMapper mapper) 59 | { 60 | var uiUser1 = new UserViewModel 61 | { 62 | Id = 1, 63 | Name = "user 1", 64 | Advertisements = new List 65 | { 66 | new AdvertisementViewModel 67 | { 68 | Id = 1, 69 | Title = "Adv 1", 70 | UserId = 1 71 | }, 72 | new AdvertisementViewModel 73 | { 74 | Id = 2, 75 | Title = "Adv 2", 76 | UserId = 1 77 | } 78 | } 79 | }; 80 | 81 | using (var ctx = new MyContext()) 82 | { 83 | var dbUser1 = ctx.Users.Include(user => user.Advertisements).First(x => x.Id == uiUser1.Id); 84 | mapper.Map(source: uiUser1, destination: dbUser1); 85 | 86 | foreach (var uiUserAdvertisement in uiUser1.Advertisements) 87 | { 88 | var dbUserAdvertisement = dbUser1.Advertisements.FirstOrDefault(ad => ad.Id == uiUserAdvertisement.Id); 89 | if (dbUserAdvertisement == null) 90 | { 91 | // Add new record 92 | var advertisement = mapper.Map(uiUserAdvertisement); 93 | dbUser1.Advertisements.Add(advertisement); 94 | } 95 | else 96 | { 97 | // Update the existing record 98 | mapper.Map(uiUserAdvertisement, dbUserAdvertisement); 99 | } 100 | } 101 | 102 | ctx.SaveChanges(); 103 | } 104 | } 105 | 106 | private static void mappToCollection(IMapper mapper) 107 | { 108 | using (var ctx = new MyContext()) 109 | { 110 | var adsList = ctx.Advertisements.ToList(); 111 | var adsViewModel = new List(); 112 | mapper.Map(source: adsList, destination: adsViewModel); 113 | 114 | Console.Write(adsViewModel.First().Title); 115 | } 116 | 117 | //todo: don't use this method, and try using `ctx.Advertisements.Where(...).Project().To().ToList()` 118 | } 119 | } 120 | } -------------------------------------------------------------------------------- /Sample04/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample04")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample04")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("ecf57dfd-ba41-4f25-a130-43911588d5ed")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample04/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Sample05/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using AutoMapper; 6 | 7 | namespace Sample05 8 | { 9 | 10 | public class SalaryList 11 | { 12 | public string User { set; get; } 13 | public int Month { set; get; } 14 | public decimal Salary { set; get; } 15 | } 16 | 17 | public interface ICustomerService 18 | { 19 | string Code { get; set; } 20 | string Name { get; set; } 21 | } 22 | 23 | class Program 24 | { 25 | static void Main(string[] args) 26 | { 27 | var config = new MapperConfiguration(cfg => 28 | { 29 | cfg.CreateMissingTypeMaps = true; // = Mapper.DynamicMap 30 | }); 31 | var mapper = config.CreateMapper(); 32 | 33 | interfaceDynamicMap(mapper); 34 | iqueryableToGenericList(mapper); 35 | anonymousListToGenericList(mapper); 36 | dataTableToGenericList(mapper); 37 | } 38 | 39 | private static void interfaceDynamicMap(IMapper mapper) 40 | { 41 | var anonymousObject = new 42 | { 43 | Code = "111", 44 | Name = "Test 1" 45 | }; 46 | var result = mapper.Map(anonymousObject); 47 | } 48 | 49 | private static void iqueryableToGenericList(IMapper mapper) 50 | { 51 | var query1 = new List 52 | { 53 | new SalaryList 54 | { 55 | User = "User 1", 56 | Month = 1, 57 | Salary = 100000 58 | }, 59 | new SalaryList 60 | { 61 | User = "User 2", 62 | Month = 1, 63 | Salary = 300000 64 | } 65 | }.AsQueryable(); 66 | 67 | var result = query1.Select(item => mapper.Map(item)).ToList(); ; 68 | } 69 | 70 | private static void anonymousListToGenericList(IMapper mapper) 71 | { 72 | var anonymousObject = new 73 | { 74 | User = "User 1", 75 | Month = 1, 76 | Salary = 100000 77 | }; 78 | var salary = mapper.Map(anonymousObject); 79 | 80 | var anonymousList = new[] 81 | { 82 | new 83 | { 84 | User = "User 1", 85 | Month = 1, 86 | Salary = 100000 87 | }, 88 | new 89 | { 90 | User = "User 2", 91 | Month = 1, 92 | Salary = 300000 93 | } 94 | }; 95 | var salaryList = anonymousList.Select(item => mapper.Map(item)).ToList(); 96 | } 97 | 98 | private static void dataTableToGenericList(IMapper mapper) 99 | { 100 | var dataTable = new DataTable("SalaryList"); 101 | dataTable.Columns.Add("User", typeof(string)); 102 | dataTable.Columns.Add("Month", typeof(int)); 103 | dataTable.Columns.Add("Salary", typeof(decimal)); 104 | 105 | var rnd = new Random(); 106 | for (var i = 0; i < 200; i++) 107 | dataTable.Rows.Add(string.Format("User {0}", i), rnd.Next(1, 12), rnd.Next(400, 2000)); 108 | 109 | // Moved to: https://github.com/AutoMapper/AutoMapper.Data/ 110 | // PM> Install-Package AutoMapper.Data -Pre 111 | var salaryList = mapper.Map>( 112 | dataTable.CreateDataReader()); 113 | } 114 | } 115 | } -------------------------------------------------------------------------------- /Sample05/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample05")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample05")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("2a1b333e-b246-4222-8b73-027b60a8d5e2")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample05/Sample05.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {97215178-33B3-4B49-8B61-B6A41609F787} 8 | Exe 9 | Properties 10 | Sample05 11 | Sample05 12 | v4.5 13 | 512 14 | ..\ 15 | true 16 | 631a2967 17 | 18 | 19 | 20 | AnyCPU 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | false 29 | 30 | 31 | AnyCPU 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE 36 | prompt 37 | 4 38 | false 39 | 40 | 41 | 42 | ..\packages\AutoMapper.6.0.2\lib\net45\AutoMapper.dll 43 | True 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 66 | 67 | 68 | 69 | 76 | -------------------------------------------------------------------------------- /Sample05/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Sample05/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /Sample06/Program.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Linq; 6 | using Omu.ValueInjecter; 7 | 8 | namespace Sample06 9 | { 10 | public class User 11 | { 12 | public int Id { get; set; } 13 | public string UserName { get; set; } 14 | public string Password { get; set; } 15 | public DateTime LastLogin { get; set; } 16 | } 17 | 18 | class Program 19 | { 20 | public static void RunActionMeasurePerformance(Action action) 21 | { 22 | GC.Collect(); 23 | var initMemUsage = Process.GetCurrentProcess().WorkingSet64; 24 | var stopwatch = new Stopwatch(); 25 | stopwatch.Start(); 26 | action(); 27 | stopwatch.Stop(); 28 | var currentMemUsage = Process.GetCurrentProcess().WorkingSet64; 29 | var memUsage = currentMemUsage - initMemUsage; 30 | if (memUsage < 0) memUsage = 0; 31 | Console.WriteLine("Elapsed time: {0}, Memory Usage: {1:N2} KB", stopwatch.Elapsed.TotalSeconds, memUsage / 1024); 32 | } 33 | 34 | 35 | static void Main(string[] args) 36 | { 37 | var length = 1000000; 38 | var users = new List(length); 39 | for (var i = 0; i < length; i++) 40 | { 41 | 42 | var user = new User 43 | { 44 | Id = i, 45 | UserName = string.Format("User{0}", i), 46 | Password = string.Format("1{0}2{0}", i), 47 | LastLogin = DateTime.Now 48 | }; 49 | users.Add(user); 50 | } 51 | 52 | Console.WriteLine("Custom mapping"); 53 | RunActionMeasurePerformance(() => 54 | { 55 | var userList = 56 | users.Select( 57 | o => 58 | new User 59 | { 60 | Id = o.Id, 61 | UserName = o.UserName, 62 | Password = o.Password, 63 | LastLogin = o.LastLogin 64 | }).ToList(); 65 | }); 66 | 67 | Console.WriteLine("EmitMapper mapping"); 68 | RunActionMeasurePerformance(() => 69 | { 70 | var map = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper(); 71 | var emitUsers = users.Select(o => map.Map(o)).ToList(); 72 | }); 73 | 74 | Console.WriteLine("ValueInjecter mapping"); 75 | RunActionMeasurePerformance(() => 76 | { 77 | var valueUsers = users.Select(o => (User)new User().InjectFrom(o)).ToList(); 78 | }); 79 | 80 | Console.WriteLine("AutoMapper mapping, DynamicMap using List"); 81 | 82 | var config = new MapperConfiguration(cfg => 83 | { 84 | cfg.CreateMissingTypeMaps = true; // = Mapper.DynamicMap 85 | }); 86 | var mapper = config.CreateMapper(); 87 | 88 | RunActionMeasurePerformance(() => 89 | { 90 | var userMap = mapper.Map>(users).ToList(); 91 | }); 92 | 93 | Console.WriteLine("AutoMapper mapping, Map using List"); 94 | RunActionMeasurePerformance(() => 95 | { 96 | var userMap = mapper.Map>(users).ToList(); 97 | }); 98 | 99 | Console.WriteLine("AutoMapper mapping, Map using IEnumerable"); 100 | RunActionMeasurePerformance(() => 101 | { 102 | var userMap = mapper.Map>(users).ToList(); 103 | }); 104 | 105 | 106 | Console.WriteLine("Press a key ..."); 107 | Console.ReadKey(); 108 | } 109 | } 110 | } -------------------------------------------------------------------------------- /Sample06/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample06")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample06")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("c6c2ce9b-b52a-4cd2-bad8-56edb506b356")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample06/Sample06.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {70924CA3-0B68-4070-8393-71572D17BBCA} 8 | Exe 9 | Properties 10 | Sample06 11 | Sample06 12 | v4.5 13 | 512 14 | ..\ 15 | true 16 | f6ee9fdd 17 | 18 | 19 | 20 | AnyCPU 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | false 29 | 30 | 31 | AnyCPU 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE 36 | prompt 37 | 4 38 | false 39 | 40 | 41 | 42 | ..\packages\AutoMapper.6.0.2\lib\net45\AutoMapper.dll 43 | True 44 | 45 | 46 | ..\packages\EmitMapper.1.0.0\lib\EmitMapper.dll 47 | True 48 | 49 | 50 | ..\packages\valueinjecter.3.1.1.3\lib\net40\Omu.ValueInjecter.dll 51 | True 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 74 | 75 | 76 | 77 | 78 | 79 | 86 | -------------------------------------------------------------------------------- /Sample06/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Sample06/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sample07/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Sample07/IoCConfig/AutomapperRegistry.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using AutoMapper; 4 | using StructureMap.Configuration.DSL; 5 | 6 | namespace Sample07.IoCConfig 7 | { 8 | public class AutoMapperRegistry : Registry 9 | { 10 | public AutoMapperRegistry() 11 | { 12 | var profiles = 13 | typeof(AutoMapperRegistry).Assembly.GetTypes() 14 | .Where(t => typeof(Profile).IsAssignableFrom(t)) 15 | .Select(t => (Profile)Activator.CreateInstance(t)); 16 | 17 | var config = new MapperConfiguration(cfg => 18 | { 19 | foreach (var profile in profiles) 20 | { 21 | cfg.AddProfile(profile); 22 | } 23 | }); 24 | 25 | For().Use(config); 26 | For().Use(ctx => ctx.GetInstance().CreateMapper(ctx.GetInstance)); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Sample07/IoCConfig/SmObjectFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Configuration; 3 | using System.Threading; 4 | using Sample07.Services; 5 | using Sample07.Services.Contracts; 6 | using StructureMap; 7 | 8 | namespace Sample07.IoCConfig 9 | { 10 | public static class SmObjectFactory 11 | { 12 | private static readonly Lazy _containerBuilder = 13 | new Lazy(defaultContainer, LazyThreadSafetyMode.ExecutionAndPublication); 14 | 15 | public static IContainer Container 16 | { 17 | get { return _containerBuilder.Value; } 18 | } 19 | 20 | private static Container defaultContainer() 21 | { 22 | var container = new Container(cfg => 23 | { 24 | var connection1 = ConfigurationManager.ConnectionStrings["Connection1"].ConnectionString; 25 | 26 | cfg.AddRegistry(); 27 | 28 | cfg.For().Use() 29 | .Ctor("connectionString").Is(connection1); 30 | 31 | cfg.For().Use() 32 | .Ctor("connectionString").Is(connection1); 33 | 34 | cfg.Scan(scan => 35 | { 36 | scan.AssemblyContainingType(); // for other asms, if any. 37 | scan.WithDefaultConventions(); 38 | }); 39 | }); 40 | return container; 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /Sample07/MappingProfiles/AdvertisementsProfile.cs: -------------------------------------------------------------------------------- 1 | using System.Data; 2 | using AutoMapper; 3 | using Sample07.Models; 4 | 5 | namespace Sample07.MappingProfiles 6 | { 7 | public class AdvertisementsProfile : Profile 8 | { 9 | public AdvertisementsProfile() 10 | { 11 | this.CreateMap() 12 | .ForMember(dest => dest.TitleWithOtherName, 13 | options => options.MapFrom(src => 14 | src.GetString(src.GetOrdinal("Title")))); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Sample07/MappingProfiles/UsersProfile.cs: -------------------------------------------------------------------------------- 1 | using System.Data; 2 | using AutoMapper; 3 | using Sample07.Models; 4 | 5 | namespace Sample07.MappingProfiles 6 | { 7 | public class UsersProfile : Profile 8 | { 9 | public UsersProfile() 10 | { 11 | this.CreateMap(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Sample07/Models/Advertisement.cs: -------------------------------------------------------------------------------- 1 | namespace Sample07.Models 2 | { 3 | public class Advertisement 4 | { 5 | public int Id { set; get; } 6 | public string Title { get; set; } 7 | public string Description { get; set; } 8 | public int UserId { get; set; } 9 | 10 | public string TitleWithOtherName { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /Sample07/Models/User.cs: -------------------------------------------------------------------------------- 1 | namespace Sample07.Models 2 | { 3 | public class User 4 | { 5 | public int Id { set; get; } 6 | public string Name { set; get; } 7 | } 8 | } -------------------------------------------------------------------------------- /Sample07/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Sample07.IoCConfig; 3 | using Sample07.Services.Contracts; 4 | 5 | namespace Sample07 6 | { 7 | class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | printUsers(); 12 | printAdvertisements(); 13 | } 14 | 15 | private static void printUsers() 16 | { 17 | var usersService = SmObjectFactory.Container.GetInstance(); 18 | 19 | var allUsers = usersService.GetAll(); 20 | foreach (var user in allUsers) 21 | { 22 | Console.WriteLine(user.Name); 23 | } 24 | 25 | var user1 = usersService.GetById(1); 26 | if (user1 != null) 27 | { 28 | Console.WriteLine(user1.Name); 29 | } 30 | } 31 | 32 | private static void printAdvertisements() 33 | { 34 | var advertisementsService = SmObjectFactory.Container.GetInstance(); 35 | 36 | var advertisements = advertisementsService.GetAll(); 37 | foreach (var advertisement in advertisements) 38 | { 39 | Console.WriteLine(advertisement.Title); 40 | } 41 | 42 | var ad1 = advertisementsService.GetById(1); 43 | if (ad1 != null) 44 | { 45 | Console.WriteLine(ad1.Title); 46 | } 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /Sample07/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample07")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample07")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("02f9d9c5-e9df-4ee0-ab3d-08b3244f334d")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample07/Sample07.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {74DEA822-CFB0-4201-BFB4-1574B40BCEF3} 8 | Exe 9 | Properties 10 | Sample07 11 | Sample07 12 | v4.5 13 | 512 14 | ..\ 15 | true 16 | 95d51e2b 17 | 18 | 19 | 20 | AnyCPU 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | false 29 | 30 | 31 | AnyCPU 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE 36 | prompt 37 | 4 38 | false 39 | 40 | 41 | 42 | ..\packages\AutoMapper.6.0.2\lib\net45\AutoMapper.dll 43 | True 44 | 45 | 46 | ..\packages\structuremap.3.1.5.154\lib\net40\StructureMap.dll 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 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 81 | 82 | 83 | 84 | 85 | 86 | 93 | -------------------------------------------------------------------------------- /Sample07/Services/AdoMapper.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Data; 3 | using System.Data.SqlClient; 4 | using AutoMapper; 5 | 6 | namespace Sample07.Services 7 | { 8 | public abstract class AdoMapper where T : class 9 | { 10 | private readonly IMapper _mapper; 11 | private readonly SqlConnection _connection; 12 | 13 | protected AdoMapper(string connectionString, IMapper mapper) 14 | { 15 | _mapper = mapper; 16 | _connection = new SqlConnection(connectionString); 17 | } 18 | 19 | protected virtual IEnumerable ExecuteCommand(SqlCommand command) 20 | { 21 | command.Connection = _connection; 22 | command.CommandType = CommandType.StoredProcedure; 23 | _connection.Open(); 24 | 25 | try 26 | { 27 | var reader = command.ExecuteReader(); 28 | try 29 | { 30 | return _mapper.Map>(reader); 31 | } 32 | finally 33 | { 34 | reader.Close(); 35 | } 36 | } 37 | finally 38 | { 39 | _connection.Close(); 40 | } 41 | } 42 | 43 | protected virtual T GetRecord(SqlCommand command) 44 | { 45 | command.Connection = _connection; 46 | _connection.Open(); 47 | try 48 | { 49 | var reader = command.ExecuteReader(); 50 | try 51 | { 52 | reader.Read(); 53 | return _mapper.Map(reader); 54 | } 55 | finally 56 | { 57 | reader.Close(); 58 | } 59 | } 60 | finally 61 | { 62 | _connection.Close(); 63 | } 64 | } 65 | 66 | protected virtual IEnumerable GetRecords(SqlCommand command) 67 | { 68 | command.Connection = _connection; 69 | _connection.Open(); 70 | try 71 | { 72 | var reader = command.ExecuteReader(); 73 | try 74 | { 75 | // moved to https://github.com/AutoMapper/AutoMapper.Data 76 | return _mapper.Map>(reader); 77 | } 78 | finally 79 | { 80 | reader.Close(); 81 | } 82 | } 83 | finally 84 | { 85 | _connection.Close(); 86 | } 87 | } 88 | } 89 | } -------------------------------------------------------------------------------- /Sample07/Services/AdvertisementsService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Data.SqlClient; 3 | using AutoMapper; 4 | using Sample07.Models; 5 | using Sample07.Services.Contracts; 6 | 7 | namespace Sample07.Services 8 | { 9 | public class AdvertisementsService : AdoMapper, IAdvertisementsService 10 | { 11 | public AdvertisementsService(string connectionString, IMapper mapper) 12 | : base(connectionString, mapper) 13 | { 14 | } 15 | 16 | public IEnumerable GetAll() 17 | { 18 | using (var command = new SqlCommand("SELECT * FROM Advertisements")) 19 | { 20 | return GetRecords(command); 21 | } 22 | } 23 | 24 | public Advertisement GetById(int id) 25 | { 26 | using (var command = new SqlCommand("SELECT * FROM Advertisements WHERE Id = @id")) 27 | { 28 | command.Parameters.Add(new SqlParameter("id", id)); 29 | return GetRecord(command); 30 | } 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Sample07/Services/Contracts/IAdvertisementsService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Sample07.Models; 3 | 4 | namespace Sample07.Services.Contracts 5 | { 6 | public interface IAdvertisementsService 7 | { 8 | IEnumerable GetAll(); 9 | Advertisement GetById(int id); 10 | } 11 | } -------------------------------------------------------------------------------- /Sample07/Services/Contracts/IUsersService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Sample07.Models; 3 | 4 | namespace Sample07.Services.Contracts 5 | { 6 | public interface IUsersService 7 | { 8 | IEnumerable GetAll(); 9 | User GetById(int id); 10 | } 11 | } -------------------------------------------------------------------------------- /Sample07/Services/UsersService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Data.SqlClient; 3 | using AutoMapper; 4 | using Sample07.Models; 5 | using Sample07.Services.Contracts; 6 | 7 | namespace Sample07.Services 8 | { 9 | public class UsersService : AdoMapper, IUsersService 10 | { 11 | public UsersService(string connectionString, IMapper mapper) 12 | : base(connectionString, mapper) 13 | { 14 | } 15 | 16 | public IEnumerable GetAll() 17 | { 18 | using (var command = new SqlCommand("SELECT * FROM Users")) 19 | { 20 | return GetRecords(command); 21 | } 22 | } 23 | 24 | public User GetById(int id) 25 | { 26 | using (var command = new SqlCommand("SELECT * FROM Users WHERE Id = @id")) 27 | { 28 | command.Parameters.Add(new SqlParameter("id", id)); 29 | return GetRecord(command); 30 | } 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Sample07/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Sample08/App.config: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Sample08/Config/Configuration.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity.Migrations; 2 | using System.Linq; 3 | using Sample08.Models; 4 | 5 | namespace Sample08.Config 6 | { 7 | public class Configuration : DbMigrationsConfiguration 8 | { 9 | public Configuration() 10 | { 11 | AutomaticMigrationsEnabled = true; 12 | AutomaticMigrationDataLossAllowed = true; 13 | } 14 | 15 | protected override void Seed(MyContext context) 16 | { 17 | if (context.Students.Any()) 18 | { 19 | return; 20 | } 21 | 22 | context.Students.Add(new Student 23 | { 24 | LastName = "LastName 1", 25 | FirstName = "FirstName 1" 26 | }); 27 | 28 | context.Students.Add(new Student 29 | { 30 | LastName = "LastName 2", 31 | FirstName = "FirstName 2" 32 | }); 33 | 34 | base.Seed(context); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Sample08/Config/InitEF.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity; 2 | 3 | namespace Sample08.Config 4 | { 5 | public static class InitEF 6 | { 7 | public static void StartDb() 8 | { 9 | Database.SetInitializer(new MigrateDatabaseToLatestVersion()); 10 | using (var context = new MyContext()) 11 | { 12 | context.Database.Initialize(force: true); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Sample08/Config/MyContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Entity; 3 | using Sample08.Models; 4 | 5 | namespace Sample08.Config 6 | { 7 | public class MyContext : DbContext 8 | { 9 | public DbSet Students { get; set; } 10 | 11 | public MyContext() 12 | : base("Connection1") 13 | { 14 | this.Database.Log = sql => Console.Write(sql); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Sample08/MappingProfiles/StudentsProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Sample08.Models; 3 | 4 | namespace Sample08.MappingProfiles 5 | { 6 | public class StudentsProfile : Profile 7 | { 8 | public StudentsProfile() 9 | { 10 | this.CreateMap(); 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Sample08/Models/Student.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | using DelegateDecompiler; 4 | 5 | namespace Sample08.Models 6 | { 7 | public class Student 8 | { 9 | public int Id { get; set; } 10 | 11 | [Required] 12 | [StringLength(450)] 13 | public string LastName { get; set; } 14 | 15 | [Required] 16 | [StringLength(450)] 17 | public string FirstName { get; set; } 18 | 19 | [NotMapped] 20 | [Computed] 21 | public string FullName 22 | { 23 | get 24 | { 25 | return LastName + ", " + FirstName; 26 | } 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Sample08/Models/StudentViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample08.Models 2 | { 3 | public class StudentViewModel 4 | { 5 | public int Id { get; set; } 6 | public string FullName { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Sample08/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using AutoMapper; 4 | using AutoMapper.QueryableExtensions; 5 | using DelegateDecompiler; 6 | using PagedList; 7 | using Sample08.Config; 8 | using Sample08.MappingProfiles; 9 | using Sample08.Models; 10 | 11 | namespace Sample08 12 | { 13 | class Program 14 | { 15 | static void Main(string[] args) 16 | { 17 | InitEF.StartDb(); 18 | var config = new MapperConfiguration(cfg => // In Application_Start() 19 | { 20 | cfg.AddProfile(); 21 | }); 22 | var mapper = config.CreateMapper(); 23 | 24 | getNamesDoesNotWork(); 25 | getFullNamesDoesNotWork(mapper); 26 | getFullNamesDoesWork(mapper); 27 | getPagedFullNamesDoesWork(mapper); 28 | } 29 | 30 | private static void getPagedFullNamesDoesWork(IMapper mapper) 31 | { 32 | using (var context = new MyContext()) 33 | { 34 | var students = context.Students 35 | .ProjectTo(mapper.ConfigurationProvider) 36 | .OrderBy(x => x.Id) 37 | .Decompile() 38 | .ToPagedList(pageNumber: 1, pageSize: 1); 39 | /* 40 | SELECT 41 | [Project1].[Id] AS [Id], 42 | [Project1].[C1] AS [C1] 43 | FROM ( SELECT 44 | [Extent1].[Id] AS [Id], 45 | [Extent1].[LastName] + N', ' + [Extent1].[FirstName] AS [C1] 46 | FROM [dbo].[Students] AS [Extent1] 47 | ) AS [Project1] 48 | ORDER BY [Project1].[Id] ASC 49 | OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY 50 | */ 51 | 52 | foreach (var student in students) 53 | { 54 | Console.WriteLine(student.FullName); 55 | } 56 | } 57 | } 58 | 59 | private static void getFullNamesDoesWork(IMapper mapper) 60 | { 61 | using (var context = new MyContext()) 62 | { 63 | var students = context.Students 64 | .ProjectTo(mapper.ConfigurationProvider) 65 | .Decompile() 66 | .ToList(); 67 | 68 | /* 69 | SELECT 70 | [Extent1].[Id] AS [Id], 71 | [Extent1].[LastName] + N', ' + [Extent1].[FirstName] AS [C1] 72 | FROM [dbo].[Students] AS [Extent1] 73 | */ 74 | 75 | foreach (var student in students) 76 | { 77 | Console.WriteLine(student.FullName); 78 | } 79 | } 80 | } 81 | 82 | private static void getFullNamesDoesNotWork(IMapper mapper) 83 | { 84 | using (var context = new MyContext()) 85 | { 86 | try 87 | { 88 | var students = context.Students.ProjectTo(mapper.ConfigurationProvider).ToList(); 89 | foreach (var student in students) 90 | { 91 | Console.WriteLine(student.FullName); 92 | } 93 | } 94 | catch (Exception ex) 95 | { 96 | Console.WriteLine(ex); 97 | } 98 | } 99 | } 100 | 101 | private static void getNamesDoesNotWork() 102 | { 103 | using (var context = new MyContext()) 104 | { 105 | try 106 | { 107 | var fullNames = context.Students.Select(x => x.FullName).ToList(); 108 | foreach (var name in fullNames) 109 | { 110 | Console.WriteLine(name); 111 | } 112 | } 113 | catch (Exception ex) 114 | { 115 | Console.WriteLine(ex); 116 | } 117 | } 118 | } 119 | } 120 | } -------------------------------------------------------------------------------- /Sample08/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample08")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample08")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("88a006d5-01d0-4e92-82cd-e13f115a12a3")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample08/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Sample09/App.config: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Sample09/Config/Configuration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data.Entity.Migrations; 4 | using System.Linq; 5 | using Sample09.Models; 6 | 7 | namespace Sample09.Config 8 | { 9 | public class Configuration : DbMigrationsConfiguration 10 | { 11 | public Configuration() 12 | { 13 | AutomaticMigrationsEnabled = true; 14 | AutomaticMigrationDataLossAllowed = true; 15 | } 16 | 17 | protected override void Seed(MyContext context) 18 | { 19 | if (context.Customers.Any()) 20 | { 21 | return; 22 | } 23 | 24 | var attr1 = context.CustomerAttributes.Add(new CustomerAttribute 25 | { 26 | Name = "Grumpy" 27 | }); 28 | 29 | var attr2 = context.CustomerAttributes.Add(new CustomerAttribute 30 | { 31 | Name = "Rich" 32 | }); 33 | 34 | var attr3 = context.CustomerAttributes.Add(new CustomerAttribute 35 | { 36 | Name = "Poor" 37 | }); 38 | 39 | var customer1 = context.Customers.Add(new Customer 40 | { 41 | Bio = null, 42 | FirstName = "F 1", 43 | LastName = "L 1", 44 | CustomerAttributes = new List { attr1, attr2 } 45 | }); 46 | 47 | var customer2 = context.Customers.Add(new Customer 48 | { 49 | Bio = "Bio 2", 50 | FirstName = "F 2", 51 | LastName = "L 2", 52 | CustomerAttributes = new List { attr1, attr3 } 53 | }); 54 | 55 | var order1 = context.Orders.Add(new Order 56 | { 57 | Customer = customer1, 58 | OrderNo = "no 1", 59 | PurchaseDate = DateTime.Now, 60 | ShipToHomeAddress = true 61 | }); 62 | 63 | var order2 = context.Orders.Add(new Order 64 | { 65 | Customer = customer1, 66 | OrderNo = "no 2", 67 | PurchaseDate = DateTime.Now, 68 | ShipToHomeAddress = true 69 | }); 70 | 71 | var order3 = context.Orders.Add(new Order 72 | { 73 | Customer = customer2, 74 | OrderNo = "no 3", 75 | PurchaseDate = DateTime.Now, 76 | ShipToHomeAddress = false 77 | }); 78 | 79 | var orderItem1 = context.OrderItems.Add(new OrderItem 80 | { 81 | Order = order1, 82 | Name = "Ord 1", 83 | Price = 1234, 84 | Quantity = 2 85 | }); 86 | 87 | var orderItem2 = context.OrderItems.Add(new OrderItem 88 | { 89 | Order = order1, 90 | Name = "Ord 2", 91 | Price = 124, 92 | Quantity = 1 93 | }); 94 | 95 | var orderItem3 = context.OrderItems.Add(new OrderItem 96 | { 97 | Order = order2, 98 | Name = "Ord 3", 99 | Price = 1244, 100 | Quantity = 1 101 | }); 102 | 103 | var orderItem4 = context.OrderItems.Add(new OrderItem 104 | { 105 | Order = order3, 106 | Name = "Ord 4", 107 | Price = 12445, 108 | Quantity = 3 109 | }); 110 | 111 | base.Seed(context); 112 | } 113 | } 114 | } -------------------------------------------------------------------------------- /Sample09/Config/InitEF.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity; 2 | 3 | namespace Sample09.Config 4 | { 5 | public static class InitEF 6 | { 7 | public static void StartDb() 8 | { 9 | Database.SetInitializer(new MigrateDatabaseToLatestVersion()); 10 | using (var context = new MyContext()) 11 | { 12 | context.Database.Initialize(force: true); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Sample09/Config/MyContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Entity; 3 | using Sample09.Models; 4 | 5 | namespace Sample09.Config 6 | { 7 | public class MyContext : DbContext 8 | { 9 | public DbSet Customers { get; set; } 10 | public DbSet CustomerAttributes { get; set; } 11 | public DbSet Orders { get; set; } 12 | public DbSet OrderItems { get; set; } 13 | 14 | public MyContext() 15 | : base("Connection1") 16 | { 17 | this.Database.Log = sql => Console.Write(sql); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Sample09/MappingsConfig/Profiles/CustomerAttributeProfile.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using AutoMapper; 4 | using Sample09.Models; 5 | using Sample09.ViewModels; 6 | 7 | namespace Sample09.MappingsConfig.Profiles 8 | { 9 | public class CustomerAttributeProfile : Profile 10 | { 11 | public CustomerAttributeProfile() 12 | { 13 | this.CreateMap, ICollection>() 14 | .ConvertUsing(); 15 | } 16 | } 17 | 18 | /// 19 | /// How to flatten nested collections 20 | /// 21 | public class CustomerListConverter : ITypeConverter, ICollection> 22 | { 23 | public ICollection Convert( 24 | ICollection source, 25 | ICollection destination, 26 | ResolutionContext context) 27 | { 28 | return source.SelectMany(customer => customer.CustomerAttributes.Select(attribute => 29 | new CustomerAttributeViewModel 30 | { 31 | AttributeName = attribute.Name, 32 | CustomerName = customer.FullName 33 | })) 34 | .ToList(); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Sample09/MappingsConfig/Profiles/CustomerProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Sample09.Models; 3 | using Sample09.ViewModels; 4 | 5 | namespace Sample09.MappingsConfig.Profiles 6 | { 7 | public class CustomerProfile : Profile 8 | { 9 | public CustomerProfile() 10 | { 11 | this.CreateMap() 12 | .ForMember(dest => dest.CustomerName, opt => opt.MapFrom(entity => entity.FullName)) 13 | .ForMember(dest => dest.Bio, opt => opt.MapFrom(entity => entity.Bio ?? "N/A")); 14 | // opt.NullSubstitute doesn't work here 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Sample09/MappingsConfig/Profiles/OrderItemsProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Sample09.Models; 3 | using Sample09.ViewModels; 4 | 5 | namespace Sample09.MappingsConfig.Profiles 6 | { 7 | public class OrderItemsProfile: Profile 8 | { 9 | public OrderItemsProfile() 10 | { 11 | this.CreateMap(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Sample09/MappingsConfig/Profiles/OrderProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using System.Linq; 3 | using Sample09.Models; 4 | using Sample09.ViewModels; 5 | 6 | namespace Sample09.MappingsConfig.Profiles 7 | { 8 | public class OrderProfile : Profile 9 | { 10 | public OrderProfile() 11 | { 12 | this.CreateMap() 13 | .ForMember(dest => dest.NumberOfOrders, 14 | opt => opt.MapFrom(src => "Number of Order(s): " + src.OrderItems.Count())) 15 | .ForMember(dest => dest.CustomerName, opt => opt.MapFrom(src => src.Customer.FullName)); 16 | 17 | this.CreateMap() 18 | .ForMember(dest => dest.ShipHome, opt => opt.MapFrom(src=>src.ShipToHomeAddress? "Yes": "No")) 19 | .ForMember(dest => dest.CustomerName, opt => opt.MapFrom(src => src.Customer.FullName)); 20 | 21 | this.CreateMap() 22 | .ForMember(dest => dest.PurchaseHour, opt => opt.MapFrom(src => src.PurchaseDate.Hour)) 23 | .ForMember(dest => dest.PurchaseMinute, opt => opt.MapFrom(src => src.PurchaseDate.Minute)) 24 | .ForMember(dest => dest.CustomerName, opt => opt.MapFrom(src => src.Customer.FullName)); 25 | 26 | this.CreateMap() 27 | .ForMember(dest => dest.OrderNumber, opt => opt.MapFrom(src => src.OrderNo)) 28 | //.ForMember(dest => dest.OrderItems, opt => opt.Ignore()) 29 | .ForMember(dest => dest.CustomerName, opt => opt.MapFrom(src => src.Customer.FullName)); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Sample09/Models/Customer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | using DelegateDecompiler; 4 | 5 | namespace Sample09.Models 6 | { 7 | public class Customer 8 | { 9 | public int Id { set; get; } 10 | public string FirstName { get; set; } 11 | public string LastName { get; set; } 12 | public string Bio { get; set; } 13 | 14 | public virtual ICollection Orders { get; set; } 15 | 16 | public virtual ICollection CustomerAttributes { get; set; } // many-to-many relationship 17 | 18 | [Computed] 19 | [NotMapped] 20 | public string FullName 21 | { 22 | get { return FirstName + ' ' + LastName; } 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Sample09/Models/CustomerAttribute.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Sample09.Models 4 | { 5 | public class CustomerAttribute 6 | { 7 | public int Id { set; get; } 8 | public string Name { set; get; } 9 | 10 | public virtual ICollection Customers { get; set; } // many-to-many relationship 11 | } 12 | } -------------------------------------------------------------------------------- /Sample09/Models/Order.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | using System.Linq; 5 | using DelegateDecompiler; 6 | 7 | namespace Sample09.Models 8 | { 9 | public class Order 10 | { 11 | public int Id { set; get; } 12 | public string OrderNo { get; set; } 13 | public DateTime PurchaseDate { get; set; } 14 | public bool ShipToHomeAddress { get; set; } 15 | 16 | public virtual ICollection OrderItems { get; set; } 17 | 18 | [ForeignKey("CustomerId")] 19 | public virtual Customer Customer { get; set; } 20 | public int CustomerId { get; set; } 21 | 22 | [Computed] 23 | [NotMapped] 24 | public decimal Total 25 | { 26 | get { return OrderItems.Sum(x => x.TotalPrice); } 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Sample09/Models/OrderItem.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | using DelegateDecompiler; 3 | 4 | namespace Sample09.Models 5 | { 6 | public class OrderItem 7 | { 8 | public int Id { get; set; } 9 | public decimal Price { get; set; } 10 | public string Name { get; set; } 11 | public int Quantity { get; set; } 12 | 13 | [ForeignKey("OrderId")] 14 | public virtual Order Order { get; set; } 15 | public int OrderId { get; set; } 16 | 17 | [Computed] 18 | [NotMapped] 19 | public decimal TotalPrice 20 | { 21 | get { return Price * Quantity; } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Sample09/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample09")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample09")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("7088cf66-c8a9-46ae-a763-b7f9daa15b93")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample09/ViewModels/CustomerAttributeViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample09.ViewModels 2 | { 3 | public class CustomerAttributeViewModel 4 | { 5 | public string AttributeName { set; get; } 6 | public string CustomerName { set; get; } 7 | } 8 | } -------------------------------------------------------------------------------- /Sample09/ViewModels/CustomerViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample09.ViewModels 2 | { 3 | public class CustomerViewModel 4 | { 5 | public string Bio { get; set; } 6 | public string CustomerName { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Sample09/ViewModels/NumberOfOrderViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample09.ViewModels 2 | { 3 | public class NumberOfOrderViewModel 4 | { 5 | public string CustomerName { get; set; } 6 | public string NumberOfOrders { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Sample09/ViewModels/OrderDateViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample09.ViewModels 2 | { 3 | public class OrderDateViewModel 4 | { 5 | public int PurchaseHour { get; set; } 6 | public int PurchaseMinute { get; set; } 7 | public string CustomerName { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Sample09/ViewModels/OrderItemsViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample09.ViewModels 2 | { 3 | public class OrderItemsViewModel 4 | { 5 | public string Name { get; set; } 6 | public int Quantity { get; set; } 7 | public decimal Price { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Sample09/ViewModels/OrderShipViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample09.ViewModels 2 | { 3 | public class OrderShipViewModel 4 | { 5 | public string ShipHome { get; set; } 6 | public string CustomerName { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Sample09/ViewModels/OrderViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Sample09.ViewModels 4 | { 5 | public class OrderViewModel 6 | { 7 | public string CustomerName { get; set; } 8 | public decimal Total { get; set; } 9 | public string OrderNumber { get; set; } 10 | public IEnumerable OrderItems { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /Sample09/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sample10/App.config: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Sample10/Config/Configuration.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity.Migrations; 2 | using System.Linq; 3 | using Sample10.Models; 4 | 5 | namespace Sample10.Config 6 | { 7 | public class Configuration : DbMigrationsConfiguration 8 | { 9 | public Configuration() 10 | { 11 | AutomaticMigrationsEnabled = true; 12 | AutomaticMigrationDataLossAllowed = true; 13 | } 14 | 15 | protected override void Seed(MyContext context) 16 | { 17 | if (context.Users.Any()) 18 | { 19 | return; 20 | } 21 | 22 | var user1 = context.Users.Add(new User 23 | { 24 | Name = "Test 1", 25 | Age = 25 26 | }); 27 | 28 | var user2 = context.Users.Add(new User 29 | { 30 | Name = "Test 2", 31 | Age = 35 32 | }); 33 | 34 | context.BlogPosts.Add(new BlogPost 35 | { 36 | Title = "Title 1", 37 | Content = "Content 1", 38 | User = user1 39 | }); 40 | 41 | context.BlogPosts.Add(new BlogPost 42 | { 43 | Title = "Title 11", 44 | Content = "Content 11", 45 | User = user1 46 | }); 47 | 48 | context.BlogPosts.Add(new BlogPost 49 | { 50 | Title = "Title 2", 51 | Content = "Content 2", 52 | User = user2 53 | }); 54 | 55 | base.Seed(context); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /Sample10/Config/InitEF.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity; 2 | 3 | namespace Sample10.Config 4 | { 5 | public static class InitEF 6 | { 7 | public static void StartDb() 8 | { 9 | Database.SetInitializer(new MigrateDatabaseToLatestVersion()); 10 | using (var context = new MyContext()) 11 | { 12 | context.Database.Initialize(force: true); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Sample10/Config/MyContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Entity; 3 | using Sample10.Models; 4 | 5 | namespace Sample10.Config 6 | { 7 | public class MyContext : DbContext 8 | { 9 | public DbSet Users { get; set; } 10 | public DbSet BlogPosts { get; set; } 11 | 12 | public MyContext() 13 | : base("Connection1") 14 | { 15 | this.Database.Log = sql => Console.Write(sql); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Sample10/MappingsConfig/TestProfile.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using AutoMapper; 3 | using Sample10.Models; 4 | using Sample10.ViewModels; 5 | 6 | namespace Sample10.MappingsConfig 7 | { 8 | public class TestProfile : Profile 9 | { 10 | public TestProfile() 11 | { 12 | this.CreateMap() 13 | .ForMember(dest => dest.CustomName, 14 | opt => opt.MapFrom(src => src.Name + "[" + src.Age + "]")) 15 | .ForMember(dest => dest.PostsCount, 16 | opt => opt.MapFrom(src => src.BlogPosts.Count())); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Sample10/Models/BlogPost.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | 3 | namespace Sample10.Models 4 | { 5 | public class BlogPost 6 | { 7 | public int Id { get; set; } 8 | public string Title { get; set; } 9 | public string Content { get; set; } 10 | 11 | [ForeignKey("UserId")] 12 | public virtual User User { get; set; } 13 | public int UserId { get; set; } 14 | } 15 | } -------------------------------------------------------------------------------- /Sample10/Models/User.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Sample10.Models 4 | { 5 | public class User 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } 9 | public int Age { get; set; } 10 | 11 | public virtual ICollection BlogPosts { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /Sample10/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using AutoMapper; 4 | using AutoMapper.QueryableExtensions; 5 | using Sample10.Config; 6 | using Sample10.MappingsConfig; 7 | using Sample10.ViewModels; 8 | 9 | namespace Sample10 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | InitEF.StartDb(); 16 | 17 | var config = new MapperConfiguration(cfg => // In Application_Start() 18 | { 19 | cfg.AddProfile(); 20 | }); 21 | config.AssertConfigurationIsValid(); 22 | 23 | var mapper = config.CreateMapper(); 24 | 25 | using (var context = new MyContext()) 26 | { 27 | var user1 = context.Users 28 | .ProjectTo(mapper.ConfigurationProvider) 29 | .FirstOrDefault(); 30 | 31 | /* 32 | SELECT 33 | [Limit1].[Id] AS [Id], 34 | [Limit1].[C1] AS [C1], 35 | [Limit1].[C2] AS [C2] 36 | FROM ( SELECT TOP (1) 37 | [Project1].[Id] AS [Id], 38 | CASE WHEN ([Project1].[Name] IS NULL) THEN N'' ELSE [Project1].[Name] END 39 | + N'[' + CAST( [Project1].[Age] AS nvarchar(max)) + N']' AS [C1], 40 | [Project1].[C1] AS [C2] 41 | FROM ( SELECT 42 | [Extent1].[Id] AS [Id], 43 | [Extent1].[Name] AS [Name], 44 | [Extent1].[Age] AS [Age], 45 | (SELECT 46 | COUNT(1) AS [A1] 47 | FROM [dbo].[BlogPosts] AS [Extent2] 48 | WHERE [Extent1].[Id] = [Extent2].[UserId]) AS [C1] 49 | FROM [dbo].[Users] AS [Extent1] 50 | ) AS [Project1] 51 | ) AS [Limit1] 52 | */ 53 | 54 | if (user1 != null) 55 | { 56 | Console.Write(user1.CustomName); 57 | Console.Write(user1.PostsCount); 58 | } 59 | } 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /Sample10/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample10")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample10")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("bed7e275-47d9-40a2-a227-34180410e15d")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample10/ViewModels/UserViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample10.ViewModels 2 | { 3 | public class UserViewModel 4 | { 5 | public int Id { set; get; } 6 | public string CustomName { set; get; } 7 | public int PostsCount { set; get; } 8 | } 9 | } -------------------------------------------------------------------------------- /Sample10/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Sample11/App.config: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Sample11/Config/Configuration.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity.Migrations; 2 | using System.Linq; 3 | using Sample11.Models; 4 | 5 | namespace Sample11.Config 6 | { 7 | public class Configuration : DbMigrationsConfiguration 8 | { 9 | public Configuration() 10 | { 11 | AutomaticMigrationsEnabled = true; 12 | AutomaticMigrationDataLossAllowed = true; 13 | } 14 | 15 | protected override void Seed(MyContext context) 16 | { 17 | if (context.Users.Any()) 18 | { 19 | return; 20 | } 21 | 22 | var user1 = context.Users.Add(new SiteUser 23 | { 24 | Name = "Test 1" 25 | }); 26 | 27 | var email1 = context.Emails.Add(new Email 28 | { 29 | Text = "tst@site.com", 30 | SiteUser = user1 31 | }); 32 | 33 | var address1 = context.Addresses.Add(new Address 34 | { 35 | Text = "Address 1", 36 | SiteUser = user1 37 | }); 38 | 39 | 40 | var user2 = context.Users.Add(new SiteUser 41 | { 42 | Name = "Test 2" 43 | }); 44 | 45 | var email2 = context.Emails.Add(new Email 46 | { 47 | Text = "name@site.com", 48 | SiteUser = user2 49 | }); 50 | 51 | var address2 = context.Addresses.Add(new Address 52 | { 53 | Text = "Address 2", 54 | SiteUser = user2 55 | }); 56 | 57 | 58 | base.Seed(context); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /Sample11/Config/InitEF.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity; 2 | 3 | namespace Sample11.Config 4 | { 5 | public static class InitEF 6 | { 7 | public static void StartDb() 8 | { 9 | Database.SetInitializer(new MigrateDatabaseToLatestVersion()); 10 | using (var context = new MyContext()) 11 | { 12 | context.Database.Initialize(force: true); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Sample11/Config/MyContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Entity; 3 | using Sample11.Models; 4 | 5 | namespace Sample11.Config 6 | { 7 | public class MyContext : DbContext 8 | { 9 | public DbSet Users { get; set; } 10 | public DbSet
Addresses { get; set; } 11 | public DbSet Emails { get; set; } 12 | 13 | public MyContext() 14 | : base("Connection1") 15 | { 16 | this.Database.Log = sql => Console.Write(sql); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Sample11/MappingsConfig/TestProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Sample11.Models; 3 | using Sample11.ViewModels; 4 | 5 | namespace Sample11.MappingsConfig 6 | { 7 | public class TestProfile : Profile 8 | { 9 | public TestProfile() 10 | { 11 | this.CreateMap() 12 | .ForMember(dest => dest.Addresses, opt => opt.ExplicitExpansion()) 13 | .ForMember(dest => dest.Emails, opt => opt.ExplicitExpansion()); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Sample11/Models/Address.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | 3 | namespace Sample11.Models 4 | { 5 | public class Address 6 | { 7 | public int Id { get; set; } 8 | public string Text { get; set; } 9 | 10 | [ForeignKey("SiteUserId")] 11 | public virtual SiteUser SiteUser { get; set; } 12 | public int SiteUserId { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /Sample11/Models/Email.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | 3 | namespace Sample11.Models 4 | { 5 | public class Email 6 | { 7 | public int Id { get; set; } 8 | public string Text { get; set; } 9 | 10 | [ForeignKey("SiteUserId")] 11 | public virtual SiteUser SiteUser { get; set; } 12 | public int SiteUserId { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /Sample11/Models/SiteUser.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Sample11.Models 4 | { 5 | public class SiteUser 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } 9 | 10 | public virtual ICollection
Addresses { get; set; } 11 | public virtual ICollection Emails { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /Sample11/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using AutoMapper; 4 | using AutoMapper.QueryableExtensions; 5 | using Sample11.Config; 6 | using Sample11.MappingsConfig; 7 | using Sample11.ViewModels; 8 | 9 | namespace Sample11 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | InitEF.StartDb(); 16 | 17 | var config = new MapperConfiguration(cfg => // In Application_Start() 18 | { 19 | cfg.AddProfile(); 20 | }); 21 | config.AssertConfigurationIsValid(); 22 | 23 | var mapper = config.CreateMapper(); 24 | 25 | using (var context = new MyContext()) 26 | { 27 | var user1 = context.Users 28 | .ProjectTo( 29 | parameters: new { }, 30 | membersToExpand: viewModel => viewModel.Emails, 31 | configuration: mapper.ConfigurationProvider) 32 | .FirstOrDefault(); 33 | 34 | /* 35 | SELECT 36 | [Project1].[Id] AS [Id], 37 | [Project1].[Name] AS [Name], 38 | [Project1].[C1] AS [C1], 39 | [Project1].[Id1] AS [Id1], 40 | [Project1].[Text] AS [Text], 41 | [Project1].[SiteUserId] AS [SiteUserId] 42 | FROM ( SELECT 43 | [Limit1].[Id] AS [Id], 44 | [Limit1].[Name] AS [Name], 45 | [Extent2].[Id] AS [Id1], 46 | [Extent2].[Text] AS [Text], 47 | [Extent2].[SiteUserId] AS [SiteUserId], 48 | CASE WHEN ([Extent2].[Id] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1] 49 | FROM (SELECT TOP (1) [c].[Id] AS [Id], [c].[Name] AS [Name] 50 | FROM [dbo].[SiteUsers] AS [c] ) AS [Limit1] 51 | LEFT OUTER JOIN [dbo].[Emails] AS [Extent2] ON [Limit1].[Id] = [Extent2].[SiteUserId] 52 | ) AS [Project1] 53 | ORDER BY [Project1].[Id] ASC, [Project1].[C1] ASC 54 | */ 55 | 56 | if (user1 != null) 57 | { 58 | foreach (var email in user1.Emails) 59 | { 60 | Console.WriteLine(email.Text); 61 | } 62 | } 63 | } 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /Sample11/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample11")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample11")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("3182d4de-95c3-49a9-b11a-07388c0f7307")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample11/ViewModels/UserViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Sample11.Models; 3 | 4 | namespace Sample11.ViewModels 5 | { 6 | public class UserViewModel 7 | { 8 | public int Id { get; set; } 9 | public string Name { get; set; } 10 | 11 | public ICollection
Addresses { get; set; } 12 | public ICollection Emails { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /Sample11/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Sample12/App_Start/FilterConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web.Mvc; 2 | 3 | namespace Sample12 4 | { 5 | public class FilterConfig 6 | { 7 | public static void RegisterGlobalFilters(GlobalFilterCollection filters) 8 | { 9 | filters.Add(new HandleErrorAttribute()); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Sample12/App_Start/RouteConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web.Mvc; 2 | using System.Web.Routing; 3 | 4 | namespace Sample12 5 | { 6 | public class RouteConfig 7 | { 8 | public static void RegisterRoutes(RouteCollection routes) 9 | { 10 | routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 11 | 12 | routes.MapRoute( 13 | name: "Default", 14 | url: "{controller}/{action}/{id}", 15 | defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 16 | ); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Sample12/App_Start/WebApiConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web.Http; 2 | 3 | namespace Sample12 4 | { 5 | public static class WebApiConfig 6 | { 7 | public static void Register(HttpConfiguration config) 8 | { 9 | config.Routes.MapHttpRoute( 10 | name: "DefaultApi", 11 | routeTemplate: "api/{controller}/{id}", 12 | defaults: new { id = RouteParameter.Optional } 13 | ); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Sample12/AutoMapperConfig/AttributeMapping/AutoMapperExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using AutoMapper; 5 | 6 | namespace Sample12.AutoMapperConfig.AttributeMapping 7 | { 8 | public static class AutoMapperExtensions 9 | { 10 | public static IEnumerable GetMappedAttributes( 11 | this IConfigurationProvider mapper, 12 | Type viewModelType, 13 | string viewModelPropertyName, 14 | IList existingAttributes) 15 | { 16 | if (viewModelType != null) 17 | { 18 | foreach (var typeMap in mapper.GetAllTypeMaps().Where(i => i.DestinationType == viewModelType)) 19 | { 20 | var propertyMaps = typeMap.GetPropertyMaps() 21 | .Where(propertyMap => !propertyMap.Ignored && propertyMap.SourceMember != null) 22 | .Where(propertyMap => propertyMap.DestinationProperty.Name == viewModelPropertyName); 23 | 24 | foreach (var propertyMap in propertyMaps) 25 | { 26 | foreach (Attribute attribute in propertyMap.SourceMember.GetCustomAttributes(true)) 27 | { 28 | if (existingAttributes.All(i => i.GetType() != attribute.GetType())) 29 | { 30 | yield return attribute; 31 | } 32 | } 33 | } 34 | } 35 | } 36 | 37 | if (existingAttributes == null) 38 | { 39 | yield break; 40 | } 41 | 42 | foreach (var attribute in existingAttributes) 43 | { 44 | yield return attribute; 45 | } 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /Sample12/AutoMapperConfig/AttributeMapping/MappedMetadataProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web.Mvc; 5 | using AutoMapper; 6 | 7 | namespace Sample12.AutoMapperConfig.AttributeMapping 8 | { 9 | public class MappedMetadataProvider : DataAnnotationsModelMetadataProvider 10 | { 11 | private readonly IConfigurationProvider _mapper; 12 | 13 | public MappedMetadataProvider(IConfigurationProvider mapper) 14 | { 15 | _mapper = mapper; 16 | } 17 | 18 | protected override ModelMetadata CreateMetadata( 19 | IEnumerable attributes, 20 | Type containerType, 21 | Func modelAccessor, 22 | Type modelType, 23 | string propertyName) 24 | { 25 | var mappedAttributes = 26 | containerType == null ? 27 | attributes : 28 | _mapper.GetMappedAttributes(containerType, propertyName, attributes.ToList()); 29 | return base.CreateMetadata(mappedAttributes, containerType, modelAccessor, modelType, propertyName); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Sample12/AutoMapperConfig/AttributeMapping/MappedValidatorProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web.Mvc; 5 | using AutoMapper; 6 | 7 | namespace Sample12.AutoMapperConfig.AttributeMapping 8 | { 9 | public class MappedValidatorProvider : DataAnnotationsModelValidatorProvider 10 | { 11 | private readonly IConfigurationProvider _mapper; 12 | 13 | public MappedValidatorProvider(IConfigurationProvider mapper) 14 | { 15 | _mapper = mapper; 16 | } 17 | 18 | protected override IEnumerable GetValidators( 19 | ModelMetadata metadata, 20 | ControllerContext context, 21 | IEnumerable attributes) 22 | { 23 | 24 | var mappedAttributes = 25 | metadata.ContainerType == null ? 26 | attributes : 27 | _mapper.GetMappedAttributes(metadata.ContainerType, metadata.PropertyName, attributes.ToList()); 28 | return base.GetValidators(metadata, context, mappedAttributes); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /Sample12/AutoMapperConfig/Mappings.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace Sample12.AutoMapperConfig 4 | { 5 | public static class Mappings 6 | { 7 | public static void RegisterMappings() 8 | { 9 | Mapper.Initialize(cfg => // In Application_Start() 10 | { 11 | cfg.AddProfile(); 12 | }); 13 | Mapper.AssertConfigurationIsValid(); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Sample12/AutoMapperConfig/UsersProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Sample12.Models; 3 | using Sample12.ViewModels; 4 | 5 | namespace Sample12.AutoMapperConfig 6 | { 7 | public class UsersProfile : Profile 8 | { 9 | public UsersProfile() 10 | { 11 | this.CreateMap(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Sample12/Content/Site.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 50px; 3 | padding-bottom: 20px; 4 | } 5 | 6 | /* Set padding to keep content from hitting the edges */ 7 | .body-content { 8 | padding-left: 15px; 9 | padding-right: 15px; 10 | } 11 | 12 | /* Override the default bootstrap behavior where horizontal description lists 13 | will truncate terms that are too long to fit in the left column 14 | */ 15 | .dl-horizontal dt { 16 | white-space: normal; 17 | } 18 | 19 | /* Set width on the form input elements since they're 100% wide by default */ 20 | input, 21 | select, 22 | textarea { 23 | max-width: 280px; 24 | } 25 | -------------------------------------------------------------------------------- /Sample12/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using System.Web.Mvc; 2 | using AutoMapper; 3 | using Sample12.Models; 4 | using Sample12.ViewModels; 5 | 6 | namespace Sample12.Controllers 7 | { 8 | public class HomeController : Controller 9 | { 10 | public ActionResult Index() 11 | { 12 | var model = new UserModel { FirstName = "و", Id = 1, LastName = "ن" }; 13 | var viewModel = Mapper.Map(model); 14 | return View(viewModel); 15 | } 16 | 17 | [HttpPost] 18 | public ActionResult Index(UserViewModel data) 19 | { 20 | return View(data); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Sample12/Global.asax: -------------------------------------------------------------------------------- 1 | <%@ Application Codebehind="Global.asax.cs" Inherits="Sample12.MvcApplication" Language="C#" %> 2 | -------------------------------------------------------------------------------- /Sample12/Global.asax.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Web.Http; 3 | using System.Web.Mvc; 4 | using System.Web.Routing; 5 | using AutoMapper; 6 | using Sample12.AutoMapperConfig; 7 | using Sample12.AutoMapperConfig.AttributeMapping; 8 | 9 | namespace Sample12 10 | { 11 | public class MvcApplication : System.Web.HttpApplication 12 | { 13 | protected void Application_Start() 14 | { 15 | AreaRegistration.RegisterAllAreas(); 16 | WebApiConfig.Register(GlobalConfiguration.Configuration); 17 | FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 18 | RouteConfig.RegisterRoutes(RouteTable.Routes); 19 | 20 | 21 | Mappings.RegisterMappings(); 22 | ModelMetadataProviders.Current = new MappedMetadataProvider(Mapper.Configuration); 23 | 24 | var modelValidatorProvider = ModelValidatorProviders.Providers 25 | .Single(provider => provider is DataAnnotationsModelValidatorProvider); 26 | ModelValidatorProviders.Providers.Remove(modelValidatorProvider); 27 | ModelValidatorProviders.Providers.Add(new MappedValidatorProvider(Mapper.Configuration)); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Sample12/Models/UserModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.Web.Mvc; 3 | 4 | namespace Sample12.Models 5 | { 6 | public class UserModel 7 | { 8 | public int Id { get; set; } 9 | 10 | [Required(ErrorMessage = "(*)")] 11 | [Display(Name = "نام")] 12 | [StringLength(maximumLength: 10, MinimumLength = 3, ErrorMessage = "نام بايد حداقل 3 و حداكثر 10 حرف باشد")] 13 | public string FirstName { get; set; } 14 | 15 | [Required(ErrorMessage = "(*)")] 16 | [Display(Name = "نام خانوادگي")] 17 | [StringLength(maximumLength: 10, MinimumLength = 3, ErrorMessage = "نام خانوادگي بايد حداقل 3 و حداكثر 10 حرف باشد")] 18 | [AdditionalMetadata("Tooltip", "براي تست")] 19 | public string LastName { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /Sample12/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample12")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample12")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("fea705c9-1b44-435b-9389-4e362efdab18")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Revision and Build Numbers 32 | // by using the '*' as shown below: 33 | [assembly: AssemblyVersion("1.0.0.0")] 34 | [assembly: AssemblyFileVersion("1.0.0.0")] 35 | -------------------------------------------------------------------------------- /Sample12/Scripts/_references.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VahidN/AutoMapperSamples/cd72c222def6b979e2ba1fa6f60bcafc235513cb/Sample12/Scripts/_references.js -------------------------------------------------------------------------------- /Sample12/Scripts/respond.min.js: -------------------------------------------------------------------------------- 1 | /* NUGET: BEGIN LICENSE TEXT 2 | * 3 | * Microsoft grants you the right to use these script files for the sole 4 | * purpose of either: (i) interacting through your browser with the Microsoft 5 | * website or online service, subject to the applicable licensing or use 6 | * terms; or (ii) using the files as included with a Microsoft product subject 7 | * to that product's license terms. Microsoft reserves all other rights to the 8 | * files not expressly granted by Microsoft, whether by implication, estoppel 9 | * or otherwise. Insofar as a script file is dual licensed under GPL, 10 | * Microsoft neither took the code under GPL nor distributes it thereunder but 11 | * under the terms set out in this paragraph. All notices and licenses 12 | * below are for informational purposes only. 13 | * 14 | * NUGET: END LICENSE TEXT */ 15 | /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ 16 | /*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */ 17 | window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.style.background="none";d.appendChild(g);return function(h){g.innerHTML='­';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document); 18 | 19 | /*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ 20 | (function(e){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=e.matchMedia&&e.matchMedia("only all").matches;if(respond.mediaQueriesSupported){return}var w=e.document,s=w.documentElement,i=[],k=[],q=[],o={},h=30,f=w.getElementsByTagName("head")[0]||s,g=w.getElementsByTagName("base")[0],b=f.getElementsByTagName("link"),d=[],a=function(){var D=b,y=D.length,B=0,A,z,C,x;for(;B-1,minw:F.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:F.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}}j()},l,r,v=function(){var z,A=w.createElement("div"),x=w.body,y=false;A.style.cssText="position:absolute;font-size:1em;width:1em";if(!x){x=y=w.createElement("body");x.style.background="none"}x.appendChild(A);s.insertBefore(x,s.firstChild);z=A.offsetWidth;if(y){s.removeChild(x)}else{x.removeChild(A)}z=p=parseFloat(z);return z},p,j=function(I){var x="clientWidth",B=s[x],H=w.compatMode==="CSS1Compat"&&B||w.body[x]||B,D={},G=b[b.length-1],z=(new Date()).getTime();if(I&&l&&z-l-1?(p||v()):1)}if(!!J){J=parseFloat(J)*(J.indexOf(y)>-1?(p||v()):1)}if(!K.hasquery||(!A||!L)&&(A||H>=C)&&(L||H<=J)){if(!D[K.media]){D[K.media]=[]}D[K.media].push(k[K.rules])}}for(var E in q){if(q[E]&&q[E].parentNode===f){f.removeChild(q[E])}}for(var E in D){var M=w.createElement("style"),F=D[E].join("\n");M.type="text/css";M.media=E;f.insertBefore(M,G.nextSibling);if(M.styleSheet){M.styleSheet.cssText=F}else{M.appendChild(w.createTextNode(F))}q.push(M)}},n=function(x,z){var y=c();if(!y){return}y.open("GET",x,true);y.onreadystatechange=function(){if(y.readyState!=4||y.status!=200&&y.status!=304){return}z(y.responseText)};if(y.readyState==4){return}y.send(null)},c=(function(){var x=false;try{x=new XMLHttpRequest()}catch(y){x=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return x}})();a();respond.update=a;function t(){j(true)}if(e.addEventListener){e.addEventListener("resize",t,false)}else{if(e.attachEvent){e.attachEvent("onresize",t)}}})(this); -------------------------------------------------------------------------------- /Sample12/ViewModels/UserViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample12.ViewModels 2 | { 3 | public class UserViewModel 4 | { 5 | public string FirstName { get; set; } 6 | public string LastName { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Sample12/Views/Home/Index.cshtml: -------------------------------------------------------------------------------- 1 | @model Sample12.ViewModels.UserViewModel 2 | @{ 3 | //var meta = ModelMetadata.FromLambdaExpression(x => x.LastName, ViewData); 4 | //var tooltip = meta.AdditionalValues["Tooltip"]; 5 | } 6 | 7 | @using (Html.BeginForm("Index", "Home", FormMethod.Post, htmlAttributes: new { @class = "form-horizontal", role = "form" })) 8 | { 9 |
10 |
11 | @Html.LabelFor(d => d.FirstName, htmlAttributes: new { @class = "col-md-2 control-label" }) 12 |
13 | @Html.TextBoxFor(d => d.FirstName) 14 | @Html.ValidationMessageFor(d => d.FirstName) 15 |
16 |
17 |
18 | @Html.LabelFor(d => d.LastName, htmlAttributes: new { @class = "col-md-2 control-label" }) 19 |
20 | @Html.TextBoxFor(d => d.LastName) 21 | @Html.ValidationMessageFor(d => d.LastName) 22 | @*@ModelMetadata.FromLambdaExpression(x => x.LastName, ViewData).AdditionalValues["Tooltip"] 23 | @tooltip*@ 24 |
25 |
26 |
27 |
28 | 29 |
30 |
31 |
32 | } -------------------------------------------------------------------------------- /Sample12/Views/Shared/Error.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = null; 3 | } 4 | 5 | 6 | 7 | 8 | 9 | Error 10 | 11 | 12 |
13 |

Error.

14 |

An error occurred while processing your request.

15 |
16 | 17 | 18 | -------------------------------------------------------------------------------- /Sample12/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | @ViewBag.Title - My ASP.NET Application 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | @RenderBody() 18 |
19 | @RenderSection("scripts", required: false) 20 | 21 | -------------------------------------------------------------------------------- /Sample12/Views/Web.config: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Sample12/Views/Web.config.bak: -------------------------------------------------------------------------------- 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 | 39 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /Sample12/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "~/Views/Shared/_Layout.cshtml"; 3 | } 4 | -------------------------------------------------------------------------------- /Sample12/Web.Debug.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 29 | 30 | -------------------------------------------------------------------------------- /Sample12/Web.Release.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 30 | 31 | -------------------------------------------------------------------------------- /Sample12/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 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 | -------------------------------------------------------------------------------- /Sample12/Web.config.bak: -------------------------------------------------------------------------------- 1 |  2 | 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 | -------------------------------------------------------------------------------- /Sample12/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Sample13/AutoMapperConfig/UsersProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Sample13.Models; 3 | using Sample13.ViewModels; 4 | 5 | namespace Sample13.AutoMapperConfig 6 | { 7 | public class UsersProfile : Profile 8 | { 9 | public UsersProfile() 10 | { 11 | string userIdentityName = null; 12 | this.CreateMap() 13 | .ForMember(d => d.UserIdentityName, opt => opt.MapFrom(src => userIdentityName)); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Sample13/Models/UserModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample13.Models 2 | { 3 | public class UserModel 4 | { 5 | public int Id { get; set; } 6 | public string FirstName { get; set; } 7 | public string LastName { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Sample13/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using AutoMapper; 5 | using AutoMapper.QueryableExtensions; 6 | using Sample13.AutoMapperConfig; 7 | using Sample13.Models; 8 | using Sample13.ViewModels; 9 | 10 | namespace Sample13 11 | { 12 | class Program 13 | { 14 | static void Main(string[] args) 15 | { 16 | var config = new MapperConfiguration(cfg => // In Application_Start() 17 | { 18 | cfg.AddProfile(); 19 | }); 20 | config.AssertConfigurationIsValid(); 21 | 22 | var mapper = config.CreateMapper(); 23 | 24 | var users = new List 25 | { 26 | new UserModel 27 | { 28 | FirstName = "f1", 29 | LastName = "l1" 30 | }, 31 | new UserModel 32 | { 33 | FirstName = "و", 34 | LastName = "ن" 35 | } 36 | }; 37 | 38 | 39 | var uiUsers = users.AsQueryable() 40 | .ProjectTo(parameters: new { userIdentityName = "User.Identity.Name Value Here" }, 41 | configuration: mapper.ConfigurationProvider) 42 | .ToList(); 43 | 44 | foreach (var user in uiUsers) 45 | { 46 | Console.WriteLine(user.FirstName); 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /Sample13/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Sample13")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Sample13")] 12 | [assembly: AssemblyCopyright("Copyright © 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("fc08a99a-ce9a-44dd-b123-91ae38b42f43")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Sample13/Sample13.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {68378414-80EC-4BAF-A010-8C87E717DFC3} 8 | Exe 9 | Properties 10 | Sample13 11 | Sample13 12 | v4.5 13 | 512 14 | ..\ 15 | true 16 | 6f2d8ff2 17 | 18 | 19 | 20 | AnyCPU 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | false 29 | 30 | 31 | AnyCPU 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE 36 | prompt 37 | 4 38 | false 39 | 40 | 41 | 42 | ..\packages\AutoMapper.6.0.2\lib\net45\AutoMapper.dll 43 | True 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 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 69 | 70 | 71 | 72 | 73 | 74 | 81 | -------------------------------------------------------------------------------- /Sample13/ViewModels/UserViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace Sample13.ViewModels 2 | { 3 | public class UserViewModel 4 | { 5 | public string FirstName { get; set; } 6 | public string LastName { get; set; } 7 | public string UserIdentityName { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Sample13/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Sample13/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Sample14/Models/Person.cs: -------------------------------------------------------------------------------- 1 | namespace Sample14 2 | { 3 | public class Person 4 | { 5 | public long PersonId { get; set; } 6 | public string Name { get; set; } 7 | public string Family { get; set; } 8 | public PersonType PersonType { get; set; } 9 | 10 | public Person(long personId, string name, string family, PersonType personType) 11 | { 12 | PersonId = personId; 13 | Name = name; 14 | Family = family; 15 | PersonType = personType; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Sample14/Models/PersonDto.cs: -------------------------------------------------------------------------------- 1 | namespace Sample14 2 | { 3 | public class PersonDto 4 | { 5 | public long PersonId { get; set; } 6 | public string Name { get; set; } 7 | public string Family { get; set; } 8 | public PersonType PersonType { get; set; } 9 | 10 | public PersonDto(long personId, string name, string family, PersonType personType) 11 | { 12 | PersonId = personId; 13 | Name = name; 14 | Family = family; 15 | PersonType = personType; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Sample14/Models/PersonList.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | using System.Linq; 4 | 5 | namespace Sample14 6 | { 7 | public class PersonList 8 | { 9 | readonly List _list = new List(); 10 | public ReadOnlyCollection GetPersons() 11 | { 12 | if (!_list.Any()) 13 | { 14 | for (int i = 0; i < 100 * 1000; i++) 15 | { 16 | _list.Add(new Person(i + 1, "Person Name" + i, "Person Family" + i, (PersonType)(i % 2))); 17 | } 18 | 19 | } 20 | return _list.AsReadOnly(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Sample14/Models/PersonType.cs: -------------------------------------------------------------------------------- 1 | namespace Sample14 2 | { 3 | public enum PersonType 4 | { 5 | Real = 0, 6 | Legal = 1 7 | } 8 | } -------------------------------------------------------------------------------- /Sample14/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Sample14")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Sample14")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("845de8c8-dcfe-47ad-934b-9f1ed6e333a1")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Sample14/Sample14.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {845DE8C8-DCFE-47AD-934B-9F1ED6E333A1} 7 | Library 8 | Properties 9 | Sample14 10 | Sample14 11 | v4.6.1 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 10.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | ..\packages\AutoMapper.6.0.2\lib\net45\AutoMapper.dll 40 | True 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 | False 72 | 73 | 74 | False 75 | 76 | 77 | False 78 | 79 | 80 | False 81 | 82 | 83 | 84 | 85 | 86 | 87 | 94 | -------------------------------------------------------------------------------- /Sample14/UnitTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | using AutoMapper; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | 6 | namespace Sample14 7 | { 8 | [TestClass] 9 | public class UnitTests 10 | { 11 | private static ReadOnlyCollection _persons; 12 | 13 | [AssemblyInitialize] 14 | public static void Initialize(TestContext context) 15 | { 16 | Mapper.Initialize(cfg => 17 | { 18 | cfg.CreateMap(); 19 | }); 20 | Mapper.AssertConfigurationIsValid(); 21 | 22 | _persons = new PersonList().GetPersons(); 23 | } 24 | 25 | [TestMethod] 26 | public void FillPersonDtoList_UsingAutoMapper() 27 | { 28 | // act 29 | var personDtoList = Mapper.Map>(_persons); 30 | 31 | //assert 32 | Assert.AreEqual(_persons.Count, personDtoList.Count); 33 | } 34 | 35 | [TestMethod] 36 | public void FillPersonDtoList_UsingHandlyAssignment() 37 | { 38 | // act 39 | var personDtoList = new List(); 40 | foreach (var person in _persons) 41 | { 42 | personDtoList.Add(new PersonDto(person.PersonId, person.Name, person.Family, person.PersonType)); 43 | } 44 | 45 | //assert 46 | Assert.AreEqual(_persons.Count, personDtoList.Count); 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /Sample14/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | --------------------------------------------------------------------------------