├── net40 ├── packages │ ├── NUnit │ │ ├── nunit.mocks.dll │ │ └── nunit.framework.dll │ ├── EntityFramework.4.3.0 │ │ ├── tools │ │ │ ├── migrate.exe │ │ │ ├── EntityFramework.psd1 │ │ │ ├── EntityFramework.PowerShell.dll │ │ │ └── init.ps1 │ │ ├── EntityFramework.4.3.0.nupkg │ │ ├── lib │ │ │ └── net40 │ │ │ │ └── EntityFramework.dll │ │ └── Content │ │ │ ├── App.config.transform │ │ │ └── Web.config.transform │ └── repositories.config ├── Infrastructure.Data.EntityFramework │ ├── Lab │ │ ├── Readme.txt │ │ ├── IDbContextStorage.cs │ │ ├── DbContextInitializer.cs │ │ ├── WebDbContextStorage.cs │ │ ├── SimpleDbContextStorage.cs │ │ ├── UnitOfWork.cs │ │ ├── DbContextBuilder.cs │ │ └── DbContextManager.cs │ ├── EntityFrameworkExtension.cs │ ├── IObjectContextStorage.cs │ ├── ObjectContextInitializer.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── SimpleObjectContextStorage.cs │ ├── WebObjectContextStorage.cs │ ├── Infrastructure.Data.EntityFramework.csproj │ ├── UnitOfWork.cs │ ├── ObjectContextBuilder.cs │ └── ObjectContextManager.cs ├── Infrastructure.Tests │ ├── packages.config │ ├── Data │ │ ├── Specification │ │ │ ├── ProductOnSaleSpecification.cs │ │ │ └── ProductByNameSpecification.cs │ │ ├── Domain │ │ │ ├── Mapping │ │ │ │ ├── EntityMappingBase.cs │ │ │ │ ├── OrderMapping.cs │ │ │ │ ├── CustomerMapping.cs │ │ │ │ ├── OrderLineMapping.cs │ │ │ │ ├── ProductMapping.cs │ │ │ │ └── CategoryMapping.cs │ │ │ ├── Category.cs │ │ │ ├── Customer.cs │ │ │ ├── Product.cs │ │ │ ├── Order.cs │ │ │ └── OrderLine.cs │ │ ├── Lab │ │ │ ├── CustomerRepository.cs │ │ │ ├── MyDbContext.cs │ │ │ ├── DataSeedingInitializer.cs │ │ │ └── UseMyDbContextTest.cs │ │ └── Repository │ │ │ └── CustomerRepository.cs │ ├── App.config │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Infrastructure.Tests.csproj ├── readme.txt ├── Infrastructure.Model │ ├── Domain │ │ └── Entity.cs │ ├── Mapping │ │ └── EntityMapping.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Infrastructure.Model.csproj ├── Infrastructure.Data │ ├── Specification │ │ ├── AndSpecification.cs │ │ ├── OrSpecification.cs │ │ ├── ISpecification.cs │ │ ├── CompositeSpecification.cs │ │ └── Specification.cs │ ├── Extensions │ │ ├── ParameterRebinder .cs │ │ └── ExpressionExtension.cs │ ├── IUnitOfWork.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Infrastructure.Data.csproj └── Infrastructure.sln ├── net45 ├── packages │ ├── EntityFramework.5.0.0 │ │ ├── tools │ │ │ ├── migrate.exe │ │ │ ├── EntityFramework.psd1 │ │ │ ├── EntityFramework.PS3.psd1 │ │ │ ├── EntityFramework.PowerShell.dll │ │ │ ├── EntityFramework.PowerShell.Utility.dll │ │ │ ├── Redirect.config │ │ │ ├── Redirect.VS11.config │ │ │ └── about_EntityFramework.help.txt │ │ ├── EntityFramework.5.0.0.nupkg │ │ ├── lib │ │ │ ├── net40 │ │ │ │ └── EntityFramework.dll │ │ │ └── net45 │ │ │ │ └── EntityFramework.dll │ │ └── Content │ │ │ ├── App.config.transform │ │ │ └── Web.config.transform │ └── repositories.config ├── Infrastructure.Data │ ├── packages.config │ ├── IUnitOfWork.cs │ ├── App.config │ ├── Specification │ │ ├── AndSpecification.cs │ │ ├── OrSpecification.cs │ │ ├── ISpecification.cs │ │ ├── CompositeSpecification.cs │ │ └── Specification.cs │ ├── IDbContextStorage.cs │ ├── Extensions │ │ ├── ParameterRebinder .cs │ │ └── ExpressionExtension.cs │ ├── DbContextInitializer.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── WebDbContextStorage.cs │ ├── SimpleDbContextStorage.cs │ ├── Infrastructure.Data.csproj │ ├── UnitOfWork.cs │ ├── DbContextBuilder.cs │ └── DbContextManager.cs ├── Infrastructure.Tests │ ├── App.config │ ├── Data │ │ ├── Domain │ │ │ ├── Mapping │ │ │ │ ├── EntityMappingBase.cs │ │ │ │ ├── CustomerMapping.cs │ │ │ │ ├── OrderMapping.cs │ │ │ │ ├── OrderLineMapping.cs │ │ │ │ ├── ProductMapping.cs │ │ │ │ └── CategoryMapping.cs │ │ │ ├── Category.cs │ │ │ ├── Customer.cs │ │ │ ├── Product.cs │ │ │ ├── Order.cs │ │ │ └── OrderLine.cs │ │ ├── Specification │ │ │ ├── ProductOnSaleSpecification.cs │ │ │ └── ProductByNameSpecification.cs │ │ ├── CustomerRepository.cs │ │ ├── MyDbContext.cs │ │ ├── DataSeedingInitializer.cs │ │ ├── UseMyDbContextTest.cs │ │ └── RepositoryTest.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Infrastructure.Tests.csproj ├── Infrastructure.Model │ ├── Domain │ │ └── Entity.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Infrastructure.Model.csproj └── efprs-net45.sln └── MIT-LICENSE.txt /net40/packages/NUnit/nunit.mocks.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net40/packages/NUnit/nunit.mocks.dll -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/Lab/Readme.txt: -------------------------------------------------------------------------------- 1 | This folder is used as a lab to investigate the use of DbContext in EF -------------------------------------------------------------------------------- /net40/packages/NUnit/nunit.framework.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net40/packages/NUnit/nunit.framework.dll -------------------------------------------------------------------------------- /net40/packages/EntityFramework.4.3.0/tools/migrate.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net40/packages/EntityFramework.4.3.0/tools/migrate.exe -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/tools/migrate.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net45/packages/EntityFramework.5.0.0/tools/migrate.exe -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /net40/packages/EntityFramework.4.3.0/EntityFramework.4.3.0.nupkg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net40/packages/EntityFramework.4.3.0/EntityFramework.4.3.0.nupkg -------------------------------------------------------------------------------- /net40/packages/EntityFramework.4.3.0/tools/EntityFramework.psd1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net40/packages/EntityFramework.4.3.0/tools/EntityFramework.psd1 -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/EntityFramework.5.0.0.nupkg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net45/packages/EntityFramework.5.0.0/EntityFramework.5.0.0.nupkg -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/tools/EntityFramework.psd1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net45/packages/EntityFramework.5.0.0/tools/EntityFramework.psd1 -------------------------------------------------------------------------------- /net45/packages/repositories.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /net40/packages/EntityFramework.4.3.0/lib/net40/EntityFramework.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net40/packages/EntityFramework.4.3.0/lib/net40/EntityFramework.dll -------------------------------------------------------------------------------- /net40/packages/repositories.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/lib/net40/EntityFramework.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net45/packages/EntityFramework.5.0.0/lib/net40/EntityFramework.dll -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/lib/net45/EntityFramework.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net45/packages/EntityFramework.5.0.0/lib/net45/EntityFramework.dll -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/tools/EntityFramework.PS3.psd1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net45/packages/EntityFramework.5.0.0/tools/EntityFramework.PS3.psd1 -------------------------------------------------------------------------------- /net40/packages/EntityFramework.4.3.0/tools/EntityFramework.PowerShell.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net40/packages/EntityFramework.4.3.0/tools/EntityFramework.PowerShell.dll -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/tools/EntityFramework.PowerShell.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net45/packages/EntityFramework.5.0.0/tools/EntityFramework.PowerShell.dll -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/tools/EntityFramework.PowerShell.Utility.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huyrua/efprs/HEAD/net45/packages/EntityFramework.5.0.0/tools/EntityFramework.PowerShell.Utility.dll -------------------------------------------------------------------------------- /net40/readme.txt: -------------------------------------------------------------------------------- 1 | The (NUnit) test class located in the %solution folder%\Infrastructure.Tests\Data\Repository\RepositoryTest.cs is used to test the implementation. The Setup will (re-)creates database every time the test method is executed. -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/Content/App.config.transform: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/Content/Web.config.transform: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/Mapping/EntityMappingBase.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity.ModelConfiguration; 2 | using Infrastructure.Model.Domain; 3 | 4 | namespace Infrastructure.Tests.Data.Domain.Mapping 5 | { 6 | public abstract class EntityMappingBase : EntityTypeConfiguration where T : Entity 7 | { 8 | public EntityMappingBase() 9 | { 10 | HasKey(x => x.Id); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /net40/packages/EntityFramework.4.3.0/Content/App.config.transform: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /net40/packages/EntityFramework.4.3.0/Content/Web.config.transform: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /net40/Infrastructure.Model/Domain/Entity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Infrastructure.Model.Domain 7 | { 8 | public abstract class Entity 9 | { 10 | public virtual int Id 11 | { 12 | get; 13 | set; 14 | } 15 | 16 | public virtual bool IsTransient() 17 | { 18 | return Id == default(int); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /net45/Infrastructure.Model/Domain/Entity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Infrastructure.Model.Domain 7 | { 8 | public abstract class Entity 9 | { 10 | public virtual int Id 11 | { 12 | get; 13 | set; 14 | } 15 | 16 | public virtual bool IsTransient() 17 | { 18 | return Id == default(int); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Specification/ProductOnSaleSpecification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Data.Specification; 6 | using Infrastructure.Tests.Data.Domain; 7 | 8 | namespace Infrastructure.Tests.Data.Specification 9 | { 10 | public class ProductOnSaleSpecification : Specification 11 | { 12 | public ProductOnSaleSpecification() : base(p => p.Price < 100) { } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Specification/ProductOnSaleSpecification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Data.Specification; 6 | using Infrastructure.Tests.Data.Domain; 7 | 8 | namespace Infrastructure.Tests.Data.Specification 9 | { 10 | public class ProductOnSaleSpecification : Specification 11 | { 12 | public ProductOnSaleSpecification() : base(p => p.Price < 100) { } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /net40/Infrastructure.Model/Mapping/EntityMapping.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Entity.ModelConfiguration; 6 | using Infrastructure.Model.Domain; 7 | 8 | 9 | namespace Infrastructure.Model.Mapping 10 | { 11 | public abstract class EntityMapping : EntityTypeConfiguration where T : Entity 12 | { 13 | protected EntityMapping() 14 | { 15 | HasKey(x => x.Id); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/Category.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Infrastructure.Model.Domain; 3 | 4 | namespace Infrastructure.Tests.Data.Domain 5 | { 6 | public class Category : Entity 7 | { 8 | public Category() 9 | { 10 | Products = new List(); 11 | } 12 | 13 | public virtual string Name 14 | { 15 | get; 16 | set; 17 | } 18 | 19 | public virtual IList Products { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/Mapping/EntityMappingBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Entity.ModelConfiguration; 6 | using Infrastructure.Model.Domain; 7 | 8 | namespace Infrastructure.Tests.Data.Domain.Mapping 9 | { 10 | public abstract class EntityMappingBase : EntityTypeConfiguration where T : Entity 11 | { 12 | public EntityMappingBase() 13 | { 14 | HasKey(x => x.Id); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | using System.Data.Objects; 4 | 5 | namespace Infrastructure.Data 6 | { 7 | public interface IUnitOfWork : IDisposable 8 | { 9 | bool IsInTransaction { get; } 10 | 11 | void SaveChanges(); 12 | 13 | void SaveChanges(SaveOptions saveOptions); 14 | 15 | void BeginTransaction(); 16 | 17 | void BeginTransaction(IsolationLevel isolationLevel); 18 | 19 | void RollBackTransaction(); 20 | 21 | void CommitTransaction(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /net40/packages/EntityFramework.4.3.0/tools/init.ps1: -------------------------------------------------------------------------------- 1 | param($installPath, $toolsPath, $package, $project) 2 | 3 | if ([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GetName().Name -eq 'EntityFramework' }) 4 | { 5 | Write-Warning 'There is already a version of EntityFramework.dll loaded. You may need to restart Visual Studio for the commands to work properly.' 6 | } 7 | 8 | if (Get-Module | ?{ $_.Name -eq 'EntityFramework' }) 9 | { 10 | Remove-Module 'EntityFramework' 11 | } 12 | 13 | Import-Module (Join-Path $toolsPath 'EntityFramework.psd1') -ArgumentList $installPath 14 | -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/tools/Redirect.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Specification/ProductByNameSpecification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Data.Specification; 6 | using Infrastructure.Tests.Data.Domain; 7 | using System.Linq.Expressions; 8 | 9 | namespace Infrastructure.Tests.Data.Specification 10 | { 11 | public class ProductByNameSpecification : Specification 12 | { 13 | public ProductByNameSpecification(string nameToMatch) 14 | : base(p => p.Name == nameToMatch) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Specification/ProductByNameSpecification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Data.Specification; 6 | using Infrastructure.Tests.Data.Domain; 7 | using System.Linq.Expressions; 8 | 9 | namespace Infrastructure.Tests.Data.Specification 10 | { 11 | public class ProductByNameSpecification : Specification 12 | { 13 | public ProductByNameSpecification(string nameToMatch) 14 | : base(p => p.Name == nameToMatch) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/Mapping/CustomerMapping.cs: -------------------------------------------------------------------------------- 1 | namespace Infrastructure.Tests.Data.Domain.Mapping 2 | { 3 | public class CustomerMapping : EntityMappingBase 4 | { 5 | public CustomerMapping() 6 | { 7 | HasKey(x => x.Id); 8 | 9 | Property(x => x.Firstname).IsRequired().HasMaxLength(25); 10 | Property(x => x.Lastname).IsRequired().HasMaxLength(25); 11 | Property(x => x.Inserted); 12 | 13 | HasMany(x => x.Orders) 14 | .WithRequired(y => y.Customer); 15 | 16 | ToTable("Customer"); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/Mapping/OrderMapping.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace Infrastructure.Tests.Data.Domain.Mapping 3 | { 4 | public class OrderMapping : EntityMappingBase 5 | { 6 | public OrderMapping() 7 | { 8 | HasKey(x => x.Id); 9 | 10 | Property(x => x.OrderDate); 11 | Property(x => x.CustomerId); 12 | 13 | HasRequired(x => x.Customer) 14 | .WithMany(y => y.Orders) 15 | .HasForeignKey(o => o.CustomerId); 16 | 17 | ToTable("Order"); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/Category.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure; 6 | using Infrastructure.Model.Domain; 7 | using System.ComponentModel.DataAnnotations; 8 | 9 | namespace Infrastructure.Tests.Data.Domain 10 | { 11 | public class Category : Entity 12 | { 13 | public Category() 14 | { 15 | Products = new List(); 16 | } 17 | 18 | public virtual string Name 19 | { 20 | get; 21 | set; 22 | } 23 | 24 | public virtual IList Products { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/Customer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Infrastructure.Model.Domain; 4 | 5 | namespace Infrastructure.Tests.Data.Domain 6 | { 7 | public class Customer : Entity 8 | { 9 | public Customer() 10 | { 11 | Orders = new List(); 12 | } 13 | 14 | public virtual string Firstname 15 | { 16 | get; set; 17 | } 18 | 19 | public virtual string Lastname 20 | { 21 | get; set; 22 | } 23 | 24 | public virtual IList Orders 25 | { 26 | get; 27 | set; 28 | } 29 | 30 | public virtual DateTime Inserted 31 | { 32 | get; set; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/Mapping/OrderMapping.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Tests.Data.Domain; 6 | using System.Data.Entity.ModelConfiguration; 7 | 8 | namespace Infrastructure.Tests.Data.Domain.Mapping 9 | { 10 | public class OrderMapping : EntityMappingBase 11 | { 12 | public OrderMapping() 13 | { 14 | HasKey(x => x.Id); 15 | 16 | Property(x => x.OrderDate); 17 | Property(x => x.CustomerId); 18 | 19 | HasRequired(x => x.Customer) 20 | .WithMany(y => y.Orders) 21 | .HasForeignKey(o => o.CustomerId); 22 | 23 | ToTable("Order"); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/Mapping/CustomerMapping.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Tests.Data.Domain; 6 | using System.Data.Entity.ModelConfiguration; 7 | 8 | namespace Infrastructure.Tests.Data.Domain.Mapping 9 | { 10 | public class CustomerMapping : EntityMappingBase 11 | { 12 | public CustomerMapping() 13 | { 14 | HasKey(x => x.Id); 15 | 16 | Property(x => x.Firstname).IsRequired().HasMaxLength(25); 17 | Property(x => x.Lastname).IsRequired().HasMaxLength(25); 18 | Property(x => x.Inserted); 19 | 20 | HasMany(x => x.Orders) 21 | .WithRequired(y => y.Customer); 22 | 23 | ToTable("Customerz"); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/tools/Redirect.VS11.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/Specification/AndSpecification.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Infrastructure.Data.Extensions; 3 | 4 | namespace Infrastructure.Data.Specification 5 | { 6 | public class AndSpecification : CompositeSpecification 7 | { 8 | public AndSpecification(Specification leftSide, Specification rightSide) 9 | : base(leftSide, rightSide) 10 | { 11 | } 12 | 13 | public override TEntity SatisfyingEntityFrom(IQueryable query) 14 | { 15 | return SatisfyingEntitiesFrom(query).FirstOrDefault(); 16 | } 17 | 18 | public override IQueryable SatisfyingEntitiesFrom(IQueryable query) 19 | { 20 | return query.Where(_leftSide.Predicate.And(_rightSide.Predicate)); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/Specification/OrSpecification.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Infrastructure.Data.Extensions; 3 | 4 | namespace Infrastructure.Data.Specification 5 | { 6 | public class OrSpecification : CompositeSpecification 7 | { 8 | public OrSpecification(Specification leftSide, Specification rightSide) 9 | : base(leftSide, rightSide) 10 | { 11 | } 12 | 13 | public override TEntity SatisfyingEntityFrom(IQueryable query) 14 | { 15 | return SatisfyingEntitiesFrom(query).FirstOrDefault(); 16 | } 17 | 18 | public override IQueryable SatisfyingEntitiesFrom(IQueryable query) 19 | { 20 | return query.Where(_leftSide.Predicate.Or(_rightSide.Predicate)); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/Customer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Model.Domain; 6 | 7 | 8 | namespace Infrastructure.Tests.Data.Domain 9 | { 10 | public class Customer : Entity 11 | { 12 | public Customer() 13 | { 14 | Orders = new List(); 15 | } 16 | 17 | public virtual string Firstname 18 | { 19 | get; set; 20 | } 21 | 22 | public virtual string Lastname 23 | { 24 | get; set; 25 | } 26 | 27 | public virtual IList Orders 28 | { 29 | get; 30 | set; 31 | } 32 | 33 | public virtual DateTime Inserted 34 | { 35 | get; set; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/Specification/ISpecification.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace Infrastructure.Data.Specification 4 | { 5 | /// 6 | /// In simple terms, a specification is a small piece of logic which is independent and give an answer 7 | /// to the question “does this match ?”. With Specification, we isolate the logic that do the selection 8 | /// into a reusable business component that can be passed around easily from the entity we are selecting. 9 | /// 10 | /// 11 | /// 12 | public interface ISpecification 13 | { 14 | TEntity SatisfyingEntityFrom(IQueryable query); 15 | 16 | IQueryable SatisfyingEntitiesFrom(IQueryable query); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/Mapping/OrderLineMapping.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace Infrastructure.Tests.Data.Domain.Mapping 3 | { 4 | public class OrderLineMapping : EntityMappingBase 5 | { 6 | public OrderLineMapping() 7 | { 8 | HasKey(x => x.Id); 9 | 10 | Property(x => x.Price); 11 | Property(x => x.Quantity); 12 | Property(x => x.ProductId); 13 | Property(x => x.OrderId); 14 | 15 | HasRequired(x => x.Order) 16 | .WithMany(o => o.OrderLines) 17 | .HasForeignKey(ol => ol.OrderId); 18 | 19 | HasRequired(x => x.Product) 20 | .WithMany(p => p.OrderLines) 21 | .HasForeignKey(ol => ol.ProductId); 22 | 23 | ToTable("OrderLine"); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data/Specification/AndSpecification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Linq.Expressions; 6 | using Infrastructure.Data.Extensions; 7 | 8 | namespace Infrastructure.Data.Specification 9 | { 10 | public class AndSpecification : CompositeSpecification 11 | { 12 | public AndSpecification(Specification leftSide, Specification rightSide) 13 | : base(leftSide, rightSide) 14 | { 15 | } 16 | 17 | public override TEntity SatisfyingEntityFrom(IQueryable query) 18 | { 19 | return SatisfyingEntitiesFrom(query).FirstOrDefault(); 20 | } 21 | 22 | public override IQueryable SatisfyingEntitiesFrom(IQueryable query) 23 | { 24 | return query.Where(_leftSide.Predicate.And(_rightSide.Predicate)); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data/Specification/OrSpecification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Linq.Expressions; 6 | using Infrastructure.Data.Extensions; 7 | 8 | namespace Infrastructure.Data.Specification 9 | { 10 | public class OrSpecification : CompositeSpecification 11 | { 12 | public OrSpecification(Specification leftSide, Specification rightSide) 13 | : base(leftSide, rightSide) 14 | { 15 | } 16 | 17 | public override TEntity SatisfyingEntityFrom(IQueryable query) 18 | { 19 | return SatisfyingEntitiesFrom(query).FirstOrDefault(); 20 | } 21 | 22 | public override IQueryable SatisfyingEntitiesFrom(IQueryable query) 23 | { 24 | return query.Where(_leftSide.Predicate.Or(_rightSide.Predicate)); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data/Specification/ISpecification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Linq.Expressions; 6 | 7 | namespace Infrastructure.Data.Specification 8 | { 9 | /// 10 | /// In simple terms, a specification is a small piece of logic which is independent and give an answer 11 | /// to the question “does this match ?”. With Specification, we isolate the logic that do the selection 12 | /// into a reusable business component that can be passed around easily from the entity we are selecting. 13 | /// 14 | /// 15 | /// 16 | public interface ISpecification 17 | { 18 | TEntity SatisfyingEntityFrom(IQueryable query); 19 | 20 | IQueryable SatisfyingEntitiesFrom(IQueryable query); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/Specification/CompositeSpecification.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace Infrastructure.Data.Specification 4 | { 5 | /// 6 | /// http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx 7 | /// 8 | /// 9 | public abstract class CompositeSpecification : ISpecification 10 | { 11 | protected readonly Specification _leftSide; 12 | protected readonly Specification _rightSide; 13 | 14 | public CompositeSpecification(Specification leftSide, Specification rightSide) 15 | { 16 | _leftSide = leftSide; 17 | _rightSide = rightSide; 18 | } 19 | 20 | public abstract TEntity SatisfyingEntityFrom(IQueryable query); 21 | 22 | public abstract IQueryable SatisfyingEntitiesFrom(IQueryable query); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/Product.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Infrastructure.Model.Domain; 3 | 4 | namespace Infrastructure.Tests.Data.Domain 5 | { 6 | public class Product : Entity 7 | { 8 | public Product() 9 | { 10 | Categories = new List(); 11 | OrderLines = new List(); 12 | } 13 | 14 | public virtual string Name 15 | { 16 | get; 17 | set; 18 | } 19 | 20 | public virtual double Price 21 | { 22 | get; 23 | set; 24 | } 25 | 26 | public virtual string Description 27 | { 28 | get; 29 | set; 30 | } 31 | 32 | public virtual IList Categories 33 | { 34 | get; 35 | set; 36 | } 37 | 38 | public virtual IList OrderLines 39 | { 40 | get; 41 | set; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/IDbContextStorage.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Data.Entity; 3 | 4 | namespace Infrastructure.Data 5 | { 6 | /// 7 | /// Stores object context 8 | /// 9 | public interface IDbContextStorage 10 | { 11 | /// 12 | /// Gets the db context for key. 13 | /// 14 | /// The key. 15 | /// 16 | DbContext GetDbContextForKey(string key); 17 | 18 | /// 19 | /// Sets the db context for key. 20 | /// 21 | /// The key. 22 | /// The object context. 23 | void SetDbContextForKey(string key, DbContext objectContext); 24 | 25 | /// 26 | /// Gets all db contexts. 27 | /// 28 | /// 29 | IEnumerable GetAllDbContexts(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/Order.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Infrastructure.Model.Domain; 4 | 5 | namespace Infrastructure.Tests.Data.Domain 6 | { 7 | public class Order : Entity 8 | { 9 | public Order() 10 | { 11 | OrderLines = new List(); 12 | } 13 | 14 | public virtual IList OrderLines 15 | { 16 | get; 17 | set; 18 | } 19 | 20 | public virtual DateTime OrderDate 21 | { 22 | get; set; 23 | } 24 | 25 | public virtual Customer Customer 26 | { 27 | get; set; 28 | } 29 | 30 | // for information on why we want this 'extra' property, see: 31 | // http://stuartgatenby.com/ef/2011/03/05/entity-framework-relationship-mapping-best-of-both-worlds-ef4-1ctp5-code-only-fluent-api/ 32 | public virtual int CustomerId 33 | { 34 | get; 35 | set; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/Mapping/OrderLineMapping.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Tests.Data.Domain; 6 | using System.Data.Entity.ModelConfiguration; 7 | 8 | namespace Infrastructure.Tests.Data.Domain.Mapping 9 | { 10 | public class OrderLineMapping : EntityMappingBase 11 | { 12 | public OrderLineMapping() 13 | { 14 | HasKey(x => x.Id); 15 | 16 | Property(x => x.Price); 17 | Property(x => x.Quantity); 18 | Property(x => x.ProductId); 19 | Property(x => x.OrderId); 20 | 21 | HasRequired(x => x.Order) 22 | .WithMany(o => o.OrderLines) 23 | .HasForeignKey(ol => ol.OrderId); 24 | 25 | HasRequired(x => x.Product) 26 | .WithMany(p => p.OrderLines) 27 | .HasForeignKey(ol => ol.ProductId); 28 | 29 | ToTable("OrderLine"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data/Specification/CompositeSpecification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Infrastructure.Data.Specification 7 | { 8 | /// 9 | /// http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx 10 | /// 11 | /// 12 | public abstract class CompositeSpecification : ISpecification 13 | { 14 | protected readonly Specification _leftSide; 15 | protected readonly Specification _rightSide; 16 | 17 | public CompositeSpecification(Specification leftSide, Specification rightSide) 18 | { 19 | _leftSide = leftSide; 20 | _rightSide = rightSide; 21 | } 22 | 23 | public abstract TEntity SatisfyingEntityFrom(IQueryable query); 24 | 25 | public abstract IQueryable SatisfyingEntitiesFrom(IQueryable query); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/EntityFrameworkExtension.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Linq; 4 | using System.Data.Objects; 5 | using System.Linq.Expressions; 6 | using System.Reflection; 7 | 8 | namespace Infrastructure.Data.EntityFramework 9 | { 10 | /// 11 | /// Adds entension methods for 12 | /// 13 | public static class IQueryableExtension 14 | { 15 | public static IQueryable Include(this IQueryable source, string path) 16 | { 17 | var objectQuery = source as ObjectQuery; 18 | if (objectQuery != null) 19 | { 20 | return objectQuery.Include(path); 21 | } 22 | return source; 23 | } 24 | 25 | public static IQueryable Include(this IQueryable mainQuery, Expression> subSelector) 26 | { 27 | return mainQuery.Include(((subSelector.Body as MemberExpression).Member as PropertyInfo).Name); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/Product.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Model.Domain; 6 | 7 | namespace Infrastructure.Tests.Data.Domain 8 | { 9 | public class Product : Entity 10 | { 11 | public Product() 12 | { 13 | Categories = new List(); 14 | OrderLines = new List(); 15 | } 16 | 17 | public virtual string Name 18 | { 19 | get; 20 | set; 21 | } 22 | 23 | public virtual double Price 24 | { 25 | get; 26 | set; 27 | } 28 | 29 | public virtual string Description 30 | { 31 | get; 32 | set; 33 | } 34 | 35 | public virtual IList Categories 36 | { 37 | get; 38 | set; 39 | } 40 | 41 | public virtual IList OrderLines 42 | { 43 | get; 44 | set; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /MIT-LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2012 Huy Nguyen and other contributors 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | 6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | 8 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/Order.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Model.Domain; 6 | 7 | namespace Infrastructure.Tests.Data.Domain 8 | { 9 | public class Order : Entity 10 | { 11 | public Order() 12 | { 13 | OrderLines = new List(); 14 | } 15 | 16 | public virtual IList OrderLines 17 | { 18 | get; 19 | set; 20 | } 21 | 22 | public virtual DateTime OrderDate 23 | { 24 | get; set; 25 | } 26 | 27 | public virtual Customer Customer 28 | { 29 | get; set; 30 | } 31 | 32 | // for information on why we want this 'extra' property, see: 33 | // http://stuartgatenby.com/ef/2011/03/05/entity-framework-relationship-mapping-best-of-both-worlds-ef4-1ctp5-code-only-fluent-api/ 34 | public virtual int CustomerId 35 | { 36 | get; 37 | set; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /net45/packages/EntityFramework.5.0.0/tools/about_EntityFramework.help.txt: -------------------------------------------------------------------------------- 1 | TOPIC 2 | about_EntityFramework 3 | 4 | SHORT DESCRIPTION 5 | Provides information about Entity Framework commands. 6 | 7 | LONG DESCRIPTION 8 | This topic describes the Entity Framework commands. Entity Framework is 9 | Microsoft's recommended data access technology for new applications. 10 | 11 | 12 | The following Entity Framework cmdlets are included. 13 | 14 | Cmdlet Description 15 | ----------------- --------------------------------------------------- 16 | Enable-Migrations Enables Code First Migrations in a project. 17 | 18 | Add-Migration Scaffolds a migration script for any pending model 19 | changes. 20 | 21 | Update-Database Applies any pending migrations to the database. 22 | 23 | Get-Migrations Displays the migrations that have been applied to 24 | the target database. 25 | 26 | SEE ALSO 27 | Enable-Migrations 28 | Add-Migration 29 | Update-Database 30 | Get-Migrations 31 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/Lab/IDbContextStorage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Entity; 6 | 7 | namespace Infrastructure.Data.EntityFramework.Lab 8 | { 9 | /// 10 | /// Stores object context 11 | /// 12 | public interface IDbContextStorage 13 | { 14 | /// 15 | /// Gets the db context for key. 16 | /// 17 | /// The key. 18 | /// 19 | DbContext GetDbContextForKey(string key); 20 | 21 | /// 22 | /// Sets the db context for key. 23 | /// 24 | /// The key. 25 | /// The object context. 26 | void SetDbContextForKey(string key, DbContext objectContext); 27 | 28 | /// 29 | /// Gets all db contexts. 30 | /// 31 | /// 32 | IEnumerable GetAllDbContexts(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/Mapping/ProductMapping.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace Infrastructure.Tests.Data.Domain.Mapping 3 | { 4 | public class ProductMapping : EntityMappingBase 5 | { 6 | public ProductMapping() 7 | { 8 | HasKey(x => x.Id); 9 | 10 | Property(x => x.Name); 11 | Property(x => x.Description); 12 | Property(x => x.Price); 13 | 14 | // many to many relationship 15 | HasMany(x => x.Categories) 16 | .WithMany(y => y.Products) 17 | .Map(m => 18 | { 19 | m.ToTable("ProductsInCategories"); 20 | m.MapLeftKey("ProductId"); // optional, to specify/override the column named ProductId (instead of auto-generated Product_Id) for a many-to-many relationship 21 | m.MapRightKey("CategoryId"); // optional, to explicitly specify the column named "CategoryId" instead of auto-generated Category_Id for a many-to-many relationship 22 | }); 23 | 24 | ToTable("Product"); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/IObjectContextStorage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Objects; 6 | 7 | namespace Infrastructure.Data.EntityFramework 8 | { 9 | /// 10 | /// Stores object context 11 | /// 12 | public interface IObjectContextStorage 13 | { 14 | /// 15 | /// Gets the object context for key. 16 | /// 17 | /// The key. 18 | /// 19 | ObjectContext GetObjectContextForKey(string key); 20 | 21 | /// 22 | /// Sets the object context for key. 23 | /// 24 | /// The key. 25 | /// The object context. 26 | void SetObjectContextForKey(string key, ObjectContext objectContext); 27 | 28 | /// 29 | /// Gets all object contexts. 30 | /// 31 | /// 32 | IEnumerable GetAllObjectContexts(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/Extensions/ParameterRebinder .cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq.Expressions; 3 | 4 | namespace Infrastructure.Data.Extensions 5 | { 6 | /// 7 | /// http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx 8 | /// 9 | public class ParameterRebinder : ExpressionVisitor 10 | { 11 | private readonly Dictionary map; 12 | 13 | public ParameterRebinder(Dictionary map) 14 | { 15 | this.map = map ?? new Dictionary(); 16 | } 17 | 18 | public static Expression ReplaceParameters(Dictionary map, Expression exp) 19 | { 20 | return new ParameterRebinder(map).Visit(exp); 21 | } 22 | 23 | protected override Expression VisitParameter(ParameterExpression p) 24 | { 25 | ParameterExpression replacement; 26 | if (map.TryGetValue(p, out replacement)) 27 | { 28 | p = replacement; 29 | } 30 | return base.VisitParameter(p); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/Mapping/CategoryMapping.cs: -------------------------------------------------------------------------------- 1 | namespace Infrastructure.Tests.Data.Domain.Mapping 2 | { 3 | public class CategoryMapping : EntityMappingBase 4 | { 5 | public CategoryMapping() 6 | { 7 | HasKey(x => x.Id); 8 | 9 | Property(x => x.Name).HasColumnName("Category Name"); 10 | 11 | //HasMany(x => x.Products) 12 | // .WithMany(y => y.Categories) 13 | // .Map(m => 14 | // { 15 | // m.ToTable("ProductsInCategories"); 16 | // }); 17 | 18 | //HasMany(x => x.Products) 19 | // .WithMany(y => y.Categories) 20 | // .Map(m => 21 | // { 22 | // m.ToTable("ProductsInCategories"); 23 | // m.MapLeftKey("CategoryId"); // optional, to specify/override the column named ProductId (instead of auto-generated Product_Id) for a many-to-many relationship 24 | // m.MapRightKey("ProductId"); // optional, to explicitly specify the column named "CategoryId" instead of auto-generated Category_Id for a many-to-many relationship 25 | // }); 26 | 27 | ToTable("Category"); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/Domain/OrderLine.cs: -------------------------------------------------------------------------------- 1 | using Infrastructure.Model.Domain; 2 | 3 | namespace Infrastructure.Tests.Data.Domain 4 | { 5 | public class OrderLine : Entity 6 | { 7 | public virtual Product Product 8 | { 9 | get; set; 10 | } 11 | 12 | public virtual int Quantity 13 | { 14 | get; set; 15 | } 16 | 17 | public virtual double Price 18 | { 19 | get; set; 20 | } 21 | 22 | public virtual Order Order 23 | { 24 | get; set; 25 | } 26 | 27 | // for information on why we want this 'extra' property, see: 28 | // http://stuartgatenby.com/ef/2011/03/05/entity-framework-relationship-mapping-best-of-both-worlds-ef4-1ctp5-code-only-fluent-api/ 29 | public virtual int OrderId 30 | { 31 | get; 32 | set; 33 | } 34 | 35 | // for information on why we want this 'extra' property, see: 36 | // http://stuartgatenby.com/ef/2011/03/05/entity-framework-relationship-mapping-best-of-both-worlds-ef4-1ctp5-code-only-fluent-api/ 37 | public virtual int ProductId 38 | { 39 | get; 40 | set; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/Mapping/ProductMapping.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Tests.Data.Domain; 6 | using System.Data.Entity.ModelConfiguration; 7 | 8 | namespace Infrastructure.Tests.Data.Domain.Mapping 9 | { 10 | public class ProductMapping : EntityMappingBase 11 | { 12 | public ProductMapping() 13 | { 14 | HasKey(x => x.Id); 15 | 16 | Property(x => x.Name); 17 | Property(x => x.Description); 18 | Property(x => x.Price); 19 | 20 | // many to many relationship 21 | HasMany(x => x.Categories) 22 | .WithMany(y => y.Products) 23 | .Map(m => 24 | { 25 | m.ToTable("ProductsInCategories"); 26 | m.MapLeftKey("ProductId"); // optional, to specify/override the column named ProductId (instead of auto-generated Product_Id) for a many-to-many relationship 27 | m.MapRightKey("CategoryId"); // optional, to explicitly specify the column named "CategoryId" instead of auto-generated Category_Id for a many-to-many relationship 28 | }); 29 | 30 | ToTable("Product"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data/Extensions/ParameterRebinder .cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Linq.Expressions; 6 | 7 | namespace Infrastructure.Data.Extensions 8 | { 9 | /// 10 | /// http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx 11 | /// 12 | public class ParameterRebinder : ExpressionVisitor 13 | { 14 | private readonly Dictionary map; 15 | 16 | public ParameterRebinder(Dictionary map) 17 | { 18 | this.map = map ?? new Dictionary(); 19 | } 20 | 21 | public static Expression ReplaceParameters(Dictionary map, Expression exp) 22 | { 23 | return new ParameterRebinder(map).Visit(exp); 24 | } 25 | 26 | protected override Expression VisitParameter(ParameterExpression p) 27 | { 28 | ParameterExpression replacement; 29 | if (map.TryGetValue(p, out replacement)) 30 | { 31 | p = replacement; 32 | } 33 | return base.VisitParameter(p); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/CustomerRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Infrastructure.Data; 5 | using Infrastructure.Tests.Data.Domain; 6 | 7 | namespace Infrastructure.Tests.Data 8 | { 9 | public interface ICustomerRepository : IRepository 10 | { 11 | IList NewlySubscribed(); 12 | 13 | Customer FindByName(string firstname, string lastname); 14 | } 15 | 16 | public class CustomerRepository : Infrastructure.Data.GenericRepository, ICustomerRepository 17 | { 18 | public CustomerRepository() 19 | : base() 20 | { 21 | } 22 | 23 | public CustomerRepository(System.Data.Entity.DbContext context) 24 | : base(context) 25 | { 26 | } 27 | 28 | public IList NewlySubscribed() 29 | { 30 | var lastMonth = DateTime.Now.Date.AddMonths(-1); 31 | 32 | return GetQuery().Where(c => c.Inserted >= lastMonth) 33 | .ToList(); 34 | } 35 | 36 | public Customer FindByName(string firstname, string lastname) 37 | { 38 | return GetQuery().Where(c => c.Firstname == firstname && c.Lastname == lastname) 39 | .FirstOrDefault(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/OrderLine.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Model.Domain; 6 | 7 | namespace Infrastructure.Tests.Data.Domain 8 | { 9 | public class OrderLine : Entity 10 | { 11 | public virtual Product Product 12 | { 13 | get; set; 14 | } 15 | 16 | public virtual int Quantity 17 | { 18 | get; set; 19 | } 20 | 21 | public virtual double Price 22 | { 23 | get; set; 24 | } 25 | 26 | public virtual Order Order 27 | { 28 | get; set; 29 | } 30 | 31 | // for information on why we want this 'extra' property, see: 32 | // http://stuartgatenby.com/ef/2011/03/05/entity-framework-relationship-mapping-best-of-both-worlds-ef4-1ctp5-code-only-fluent-api/ 33 | public virtual int OrderId 34 | { 35 | get; 36 | set; 37 | } 38 | 39 | // for information on why we want this 'extra' property, see: 40 | // http://stuartgatenby.com/ef/2011/03/05/entity-framework-relationship-mapping-best-of-both-worlds-ef4-1ctp5-code-only-fluent-api/ 41 | public virtual int ProductId 42 | { 43 | get; 44 | set; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Lab/CustomerRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Infrastructure.Data; 5 | using Infrastructure.Tests.Data.Domain; 6 | 7 | namespace Infrastructure.Tests.Data.Lab 8 | { 9 | public interface ICustomerRepository : IRepository 10 | { 11 | IList NewlySubscribed(); 12 | 13 | Customer FindByName(string firstname, string lastname); 14 | } 15 | 16 | public class CustomerRepository : Infrastructure.Data.EntityFramework.Lab.GenericRepository, ICustomerRepository 17 | { 18 | public CustomerRepository() 19 | : base() 20 | { 21 | } 22 | 23 | public CustomerRepository(System.Data.Entity.DbContext context) 24 | : base(context) 25 | { 26 | } 27 | 28 | public IList NewlySubscribed() 29 | { 30 | var lastMonth = DateTime.Now.Date.AddMonths(-1); 31 | 32 | return GetQuery().Where(c => c.Inserted >= lastMonth) 33 | .ToList(); 34 | } 35 | 36 | public Customer FindByName(string firstname, string lastname) 37 | { 38 | return GetQuery().Where(c => c.Firstname == firstname && c.Lastname == lastname) 39 | .FirstOrDefault(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Domain/Mapping/CategoryMapping.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Tests.Data.Domain; 6 | using System.Data.Entity.ModelConfiguration; 7 | 8 | namespace Infrastructure.Tests.Data.Domain.Mapping 9 | { 10 | public class CategoryMapping : EntityMappingBase 11 | { 12 | public CategoryMapping() 13 | { 14 | HasKey(x => x.Id); 15 | 16 | Property(x => x.Name).HasColumnName("Category Name"); 17 | 18 | //HasMany(x => x.Products) 19 | // .WithMany(y => y.Categories) 20 | // .Map(m => 21 | // { 22 | // m.ToTable("ProductsInCategories"); 23 | // }); 24 | 25 | //HasMany(x => x.Products) 26 | // .WithMany(y => y.Categories) 27 | // .Map(m => 28 | // { 29 | // m.ToTable("ProductsInCategories"); 30 | // m.MapLeftKey("CategoryId"); // optional, to specify/override the column named ProductId (instead of auto-generated Product_Id) for a many-to-many relationship 31 | // m.MapRightKey("ProductId"); // optional, to explicitly specify the column named "CategoryId" instead of auto-generated Category_Id for a many-to-many relationship 32 | // }); 33 | 34 | ToTable("Category"); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/DbContextInitializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Infrastructure.Data 4 | { 5 | public class DbContextInitializer 6 | { 7 | private static readonly object _syncLock = new object(); 8 | private static DbContextInitializer _instance; 9 | 10 | protected DbContextInitializer() { } 11 | 12 | private bool _isInitialized = false; 13 | 14 | public static DbContextInitializer Instance() 15 | { 16 | if (_instance == null) { 17 | lock (_syncLock) { 18 | if (_instance == null) { 19 | _instance = new DbContextInitializer(); 20 | } 21 | } 22 | } 23 | 24 | return _instance; 25 | } 26 | 27 | /// 28 | /// This is the method which should be given the call to intialize the DbContext; e.g., 29 | /// DbContextInitializer.Instance().InitializeDbContextOnce(() => InitializeDbContext()); 30 | /// where InitializeDbContext() is a method which calls DbContextManager.Init() 31 | /// 32 | /// 33 | public void InitializeDbContextOnce(Action initMethod) 34 | { 35 | lock (_syncLock) 36 | { 37 | if (!_isInitialized) 38 | { 39 | initMethod(); 40 | _isInitialized = true; 41 | } 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Repository/CustomerRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Data; 6 | using Infrastructure.Tests.Data.Domain; 7 | using System.Data.Objects; 8 | using Infrastructure.Data.EntityFramework; 9 | 10 | namespace Infrastructure.Tests.Data.Repository 11 | { 12 | public interface ICustomerRepository : IRepository 13 | { 14 | IList NewlySubscribed(); 15 | 16 | Customer FindByName(string firstname, string lastname); 17 | } 18 | 19 | /// 20 | /// demostrate an implementation of specific repository 21 | /// 22 | public class CustomerRepository : GenericRepository, ICustomerRepository 23 | { 24 | public CustomerRepository() 25 | : base() 26 | { 27 | } 28 | 29 | public CustomerRepository(ObjectContext context) 30 | : base(context) 31 | { 32 | } 33 | 34 | public IList NewlySubscribed() 35 | { 36 | var lastMonth = DateTime.Now.Date.AddMonths(-1); 37 | 38 | return GetQuery().Where(c => c.Inserted >= lastMonth) 39 | .ToList(); 40 | } 41 | 42 | public Customer FindByName(string firstname, string lastname) 43 | { 44 | return GetQuery().Where(c => c.Firstname == firstname && c.Lastname == lastname) 45 | .FirstOrDefault(); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/MyDbContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Entity; 6 | using Infrastructure.Tests.Data.Domain; 7 | using Infrastructure.Tests.Data.Domain.Mapping; 8 | using System.Data.Entity.Infrastructure; 9 | 10 | namespace Infrastructure.Tests.Data 11 | { 12 | public class MyDbContext : DbContext 13 | { 14 | public DbSet Categories { get; set; } 15 | public DbSet Products { get; set; } 16 | public DbSet Orders { get; set; } 17 | public DbSet OrderLines { get; set; } 18 | public DbSet Customers { get; set; } 19 | 20 | public MyDbContext(string connStringName) : 21 | base(connStringName) 22 | { 23 | this.Configuration.LazyLoadingEnabled = true; 24 | this.Configuration.ProxyCreationEnabled = false; 25 | } 26 | 27 | protected override void OnModelCreating(DbModelBuilder modelBuilder) 28 | { 29 | base.OnModelCreating(modelBuilder); 30 | 31 | modelBuilder.Configurations.Add(new CustomerMapping()); 32 | modelBuilder.Configurations.Add(new ProductMapping()); 33 | modelBuilder.Configurations.Add(new CategoryMapping()); 34 | modelBuilder.Configurations.Add(new OrderMapping()); 35 | modelBuilder.Configurations.Add(new OrderLineMapping()); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Lab/MyDbContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Entity; 6 | using Infrastructure.Tests.Data.Domain; 7 | using Infrastructure.Tests.Data.Domain.Mapping; 8 | using System.Data.Entity.Infrastructure; 9 | 10 | namespace Infrastructure.Tests.Data.Lab 11 | { 12 | public class MyDbContext : DbContext 13 | { 14 | public DbSet Categories { get; set; } 15 | public DbSet Products { get; set; } 16 | public DbSet Orders { get; set; } 17 | public DbSet OrderLines { get; set; } 18 | public DbSet Customers { get; set; } 19 | 20 | public MyDbContext(string connStringName) : 21 | base(connStringName) 22 | { 23 | this.Configuration.LazyLoadingEnabled = true; 24 | this.Configuration.ProxyCreationEnabled = false; 25 | } 26 | 27 | protected override void OnModelCreating(DbModelBuilder modelBuilder) 28 | { 29 | base.OnModelCreating(modelBuilder); 30 | 31 | modelBuilder.Configurations.Add(new CustomerMapping()); 32 | modelBuilder.Configurations.Add(new ProductMapping()); 33 | modelBuilder.Configurations.Add(new CategoryMapping()); 34 | modelBuilder.Configurations.Add(new OrderMapping()); 35 | modelBuilder.Configurations.Add(new OrderLineMapping()); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | using System.Data.Objects; 4 | 5 | namespace Infrastructure.Data 6 | { 7 | public interface IUnitOfWork : IDisposable 8 | { 9 | /// 10 | /// Check wether transaction is running 11 | /// 12 | bool IsInTransaction { get; } 13 | 14 | /// 15 | /// Directly save change without using Begin & Commit Transaction 16 | /// 17 | void SaveChanges(); 18 | 19 | /// 20 | /// Directly save change without using Begin & Commit Transaction with saving option 21 | /// 22 | void SaveChanges(SaveOptions saveOptions); 23 | 24 | /// 25 | /// Save change immediately than accept all change with Commit Transaction. 26 | /// 27 | void Save(); 28 | 29 | /// 30 | /// Save change immediately than accept all change with Commit Transaction with saving option 31 | /// 32 | void Save(SaveOptions saveOptions); 33 | 34 | /// 35 | /// Start transaction 36 | /// 37 | void BeginTransaction(); 38 | 39 | /// 40 | /// Start transaction with isolation level 41 | /// 42 | /// isolation level 43 | void BeginTransaction(IsolationLevel isolationLevel); 44 | 45 | /// 46 | /// Rollback transaction change 47 | /// 48 | void RollBackTransaction(); 49 | 50 | /// 51 | /// Commit all transaction change 52 | /// 53 | void CommitTransaction(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/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("Infrastructure.Data")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Microsoft")] 12 | [assembly: AssemblyProduct("Infrastructure.Data")] 13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2012")] 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("c0e7b2b8-f4ca-4995-a9e2-23997f2801cf")] 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 | -------------------------------------------------------------------------------- /net45/Infrastructure.Model/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("Infrastructure.Model")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Microsoft")] 12 | [assembly: AssemblyProduct("Infrastructure.Model")] 13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2012")] 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("f4cd4eb2-b7d9-43db-988d-5056af4173c3")] 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 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/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("Infrastructure.Tests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Microsoft")] 12 | [assembly: AssemblyProduct("Infrastructure.Tests")] 13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2012")] 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("b162dc6e-cf30-42ca-a329-24000511768d")] 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 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data/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("Infrastructure.Data")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Hewlett-Packard Company")] 12 | [assembly: AssemblyProduct("Infrastructure.Data")] 13 | [assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 2010")] 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("df14583e-3a1e-4f93-b795-d8857b25eba2")] 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 | -------------------------------------------------------------------------------- /net40/Infrastructure.Model/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("Infrastructure.Model")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Hewlett-Packard Company")] 12 | [assembly: AssemblyProduct("Infrastructure.Model")] 13 | [assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 2010")] 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("a9910c1c-7cc9-47d6-ac65-603d8f3d28d0")] 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 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/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("Infrastructure.Tests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Hewlett-Packard Company")] 12 | [assembly: AssemblyProduct("Infrastructure.Tests")] 13 | [assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 2010")] 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("466ee7df-eafd-44f7-a3e7-b9159564a6fe")] 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 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/Extensions/ExpressionExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | 5 | namespace Infrastructure.Data.Extensions 6 | { 7 | /// 8 | /// http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx 9 | /// 10 | public static class ExpressionExtension 11 | { 12 | public static Expression Compose(this Expression first, Expression second, Func merge) 13 | { 14 | // build parameter map (from parameters of second to parameters of first) 15 | var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); 16 | 17 | // replace parameters in the second lambda expression with parameters from the first 18 | var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); 19 | 20 | // apply composition of lambda expression bodies to parameters from the first expression 21 | return Expression.Lambda(merge(first.Body, secondBody), first.Parameters); 22 | } 23 | 24 | public static Expression> And(this Expression> first, Expression> second) 25 | { 26 | return first.Compose(second, Expression.And); 27 | } 28 | 29 | public static Expression> Or(this Expression> first, Expression> second) 30 | { 31 | return first.Compose(second, Expression.Or); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/ObjectContextInitializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Infrastructure.Data.EntityFramework 7 | { 8 | public class ObjectContextInitializer 9 | { 10 | private static readonly object syncLock = new object(); 11 | private static ObjectContextInitializer instance; 12 | 13 | protected ObjectContextInitializer() { } 14 | 15 | private bool isInitialized = false; 16 | 17 | public static ObjectContextInitializer Instance() 18 | { 19 | if (instance == null) { 20 | lock (syncLock) { 21 | if (instance == null) { 22 | instance = new ObjectContextInitializer(); 23 | } 24 | } 25 | } 26 | 27 | return instance; 28 | } 29 | 30 | /// 31 | /// This is the method which should be given the call to intialize the ObjectContext; e.g., 32 | /// ObjectContextInitializer.Instance().InitializeObjectContextOnce(() => InitializeObjectContext()); 33 | /// where InitializeObjectContext() is a method which calls ObjectContextManager.Init() 34 | /// 35 | /// 36 | public void InitializeObjectContextOnce(Action initMethod) { 37 | lock (syncLock) { 38 | if (!isInitialized) { 39 | initMethod(); 40 | isInitialized = true; 41 | } 42 | } 43 | } 44 | 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/Lab/DbContextInitializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Infrastructure.Data.EntityFramework.Lab 7 | { 8 | public class DbContextInitializer 9 | { 10 | private static readonly object _syncLock = new object(); 11 | private static DbContextInitializer _instance; 12 | 13 | protected DbContextInitializer() { } 14 | 15 | private bool _isInitialized = false; 16 | 17 | public static DbContextInitializer Instance() 18 | { 19 | if (_instance == null) { 20 | lock (_syncLock) { 21 | if (_instance == null) { 22 | _instance = new DbContextInitializer(); 23 | } 24 | } 25 | } 26 | 27 | return _instance; 28 | } 29 | 30 | /// 31 | /// This is the method which should be given the call to intialize the DbContext; e.g., 32 | /// DbContextInitializer.Instance().InitializeDbContextOnce(() => InitializeDbContext()); 33 | /// where InitializeDbContext() is a method which calls DbContextManager.Init() 34 | /// 35 | /// 36 | public void InitializeDbContextOnce(Action initMethod) 37 | { 38 | lock (_syncLock) 39 | { 40 | if (!_isInitialized) 41 | { 42 | initMethod(); 43 | _isInitialized = true; 44 | } 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/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("Infrastructure.Data.EntityFramework")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Hewlett-Packard Company")] 12 | [assembly: AssemblyProduct("Infrastructure.Data.EntityFramework")] 13 | [assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 2010")] 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("db28fa66-8e71-40fc-9639-09c79b03d1c8")] 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 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data/Extensions/ExpressionExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Linq.Expressions; 6 | 7 | namespace Infrastructure.Data.Extensions 8 | { 9 | /// 10 | /// http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx 11 | /// 12 | public static class ExpressionExtension 13 | { 14 | public static Expression Compose(this Expression first, Expression second, Func merge) 15 | { 16 | // build parameter map (from parameters of second to parameters of first) 17 | var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); 18 | 19 | // replace parameters in the second lambda expression with parameters from the first 20 | var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); 21 | 22 | // apply composition of lambda expression bodies to parameters from the first expression 23 | return Expression.Lambda(merge(first.Body, secondBody), first.Parameters); 24 | } 25 | 26 | public static Expression> And(this Expression> first, Expression> second) 27 | { 28 | return first.Compose(second, Expression.And); 29 | } 30 | 31 | public static Expression> Or(this Expression> first, Expression> second) 32 | { 33 | return first.Compose(second, Expression.Or); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/Specification/Specification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | using Infrastructure.Data.Extensions; 5 | 6 | namespace Infrastructure.Data.Specification 7 | { 8 | public class Specification : ISpecification 9 | { 10 | public Specification(Expression> predicate) 11 | { 12 | Predicate = predicate; 13 | } 14 | 15 | public Specification And(Specification specification) 16 | { 17 | return new Specification(this.Predicate.And(specification.Predicate)); 18 | } 19 | 20 | public Specification And(Expression> predicate) 21 | { 22 | return new Specification(this.Predicate.And(predicate)); 23 | } 24 | 25 | public Specification Or(Specification specification) 26 | { 27 | return new Specification(this.Predicate.Or(specification.Predicate)); 28 | } 29 | 30 | public Specification Or(Expression> predicate) 31 | { 32 | return new Specification(this.Predicate.Or(predicate)); 33 | } 34 | 35 | public TEntity SatisfyingEntityFrom(IQueryable query) 36 | { 37 | return query.Where(Predicate).SingleOrDefault(); 38 | } 39 | 40 | public IQueryable SatisfyingEntitiesFrom(IQueryable query) 41 | { 42 | return query.Where(Predicate); 43 | } 44 | 45 | public Expression> Predicate; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data/Specification/Specification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Linq.Expressions; 6 | using Infrastructure.Data.Extensions; 7 | 8 | namespace Infrastructure.Data.Specification 9 | { 10 | public class Specification : ISpecification 11 | { 12 | public Specification(Expression> predicate) 13 | { 14 | Predicate = predicate; 15 | } 16 | 17 | public Specification And(Specification specification) 18 | { 19 | return new Specification(this.Predicate.And(specification.Predicate)); 20 | } 21 | 22 | public Specification And(Expression> predicate) 23 | { 24 | return new Specification(this.Predicate.And(predicate)); 25 | } 26 | 27 | public Specification Or(Specification specification) 28 | { 29 | return new Specification(this.Predicate.Or(specification.Predicate)); 30 | } 31 | 32 | public Specification Or(Expression> predicate) 33 | { 34 | return new Specification(this.Predicate.Or(predicate)); 35 | } 36 | 37 | public TEntity SatisfyingEntityFrom(IQueryable query) 38 | { 39 | return query.Where(Predicate).SingleOrDefault(); 40 | } 41 | 42 | public IQueryable SatisfyingEntitiesFrom(IQueryable query) 43 | { 44 | return query.Where(Predicate); 45 | } 46 | 47 | public Expression> Predicate; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/WebDbContextStorage.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Data.Entity; 3 | using System.Web; 4 | 5 | namespace Infrastructure.Data 6 | { 7 | public class WebDbContextStorage : IDbContextStorage 8 | { 9 | public WebDbContextStorage(HttpApplication app) 10 | { 11 | app.EndRequest += (sender, args) => 12 | { 13 | DbContextManager.CloseAllDbContexts(); 14 | HttpContext.Current.Items.Remove(STORAGE_KEY); 15 | }; 16 | } 17 | 18 | public DbContext GetDbContextForKey(string key) 19 | { 20 | SimpleDbContextStorage storage = GetSimpleDbContextStorage(); 21 | return storage.GetDbContextForKey(key); 22 | } 23 | 24 | public void SetDbContextForKey(string factoryKey, DbContext context) 25 | { 26 | SimpleDbContextStorage storage = GetSimpleDbContextStorage(); 27 | storage.SetDbContextForKey(factoryKey, context); 28 | } 29 | 30 | public IEnumerable GetAllDbContexts() 31 | { 32 | SimpleDbContextStorage storage = GetSimpleDbContextStorage(); 33 | return storage.GetAllDbContexts(); 34 | } 35 | 36 | private SimpleDbContextStorage GetSimpleDbContextStorage() 37 | { 38 | HttpContext context = HttpContext.Current; 39 | SimpleDbContextStorage storage = context.Items[STORAGE_KEY] as SimpleDbContextStorage; 40 | if (storage == null) 41 | { 42 | storage = new SimpleDbContextStorage(); 43 | context.Items[STORAGE_KEY] = storage; 44 | } 45 | return storage; 46 | } 47 | 48 | private const string STORAGE_KEY = "HttpContextObjectContextStorageKey"; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/SimpleDbContextStorage.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Data.Entity; 3 | 4 | namespace Infrastructure.Data 5 | { 6 | public class SimpleDbContextStorage : IDbContextStorage 7 | { 8 | private Dictionary _storage = new Dictionary(); 9 | 10 | /// 11 | /// Initializes a new instance of the class. 12 | /// 13 | public SimpleDbContextStorage() { } 14 | 15 | /// 16 | /// Returns the db context associated with the specified key or 17 | /// null if the specified key is not found. 18 | /// 19 | /// The key. 20 | /// 21 | public DbContext GetDbContextForKey(string key) 22 | { 23 | DbContext context; 24 | if (!this._storage.TryGetValue(key, out context)) 25 | return null; 26 | return context; 27 | } 28 | 29 | 30 | /// 31 | /// Stores the db context into a dictionary using the specified key. 32 | /// If an object context already exists by the specified key, 33 | /// it gets overwritten by the new object context passed in. 34 | /// 35 | /// The key. 36 | /// The object context. 37 | public void SetDbContextForKey(string key, DbContext context) 38 | { 39 | this._storage.Add(key, context); 40 | } 41 | 42 | /// 43 | /// Returns all the values of the internal dictionary of db contexts. 44 | /// 45 | /// 46 | public IEnumerable GetAllDbContexts() 47 | { 48 | return this._storage.Values; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/Lab/WebDbContextStorage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Web; 6 | using System.Data.Objects; 7 | using System.Data.Entity; 8 | 9 | namespace Infrastructure.Data.EntityFramework.Lab 10 | { 11 | public class WebDbContextStorage : IDbContextStorage 12 | { 13 | public WebDbContextStorage(HttpApplication app) 14 | { 15 | app.EndRequest += (sender, args) => 16 | { 17 | DbContextManager.CloseAllDbContexts(); 18 | HttpContext.Current.Items.Remove(STORAGE_KEY); 19 | }; 20 | } 21 | 22 | public DbContext GetDbContextForKey(string key) 23 | { 24 | SimpleDbContextStorage storage = GetSimpleDbContextStorage(); 25 | return storage.GetDbContextForKey(key); 26 | } 27 | 28 | public void SetDbContextForKey(string factoryKey, DbContext context) 29 | { 30 | SimpleDbContextStorage storage = GetSimpleDbContextStorage(); 31 | storage.SetDbContextForKey(factoryKey, context); 32 | } 33 | 34 | public IEnumerable GetAllDbContexts() 35 | { 36 | SimpleDbContextStorage storage = GetSimpleDbContextStorage(); 37 | return storage.GetAllDbContexts(); 38 | } 39 | 40 | private SimpleDbContextStorage GetSimpleDbContextStorage() 41 | { 42 | HttpContext context = HttpContext.Current; 43 | SimpleDbContextStorage storage = context.Items[STORAGE_KEY] as SimpleDbContextStorage; 44 | if (storage == null) 45 | { 46 | storage = new SimpleDbContextStorage(); 47 | context.Items[STORAGE_KEY] = storage; 48 | } 49 | return storage; 50 | } 51 | 52 | private const string STORAGE_KEY = "HttpContextObjectContextStorageKey"; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /net45/efprs-net45.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2012 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure.Data", "Infrastructure.Data\Infrastructure.Data.csproj", "{83CE8910-37AA-415A-954B-3E36F9701D17}" 5 | EndProject 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure.Model", "Infrastructure.Model\Infrastructure.Model.csproj", "{84AEBF14-8E14-414B-9266-A750D7260CC9}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure.Tests", "Infrastructure.Tests\Infrastructure.Tests.csproj", "{4083B654-9EBA-416D-B5D1-27EBA222B831}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {4083B654-9EBA-416D-B5D1-27EBA222B831}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {4083B654-9EBA-416D-B5D1-27EBA222B831}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {4083B654-9EBA-416D-B5D1-27EBA222B831}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {4083B654-9EBA-416D-B5D1-27EBA222B831}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {83CE8910-37AA-415A-954B-3E36F9701D17}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {83CE8910-37AA-415A-954B-3E36F9701D17}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {83CE8910-37AA-415A-954B-3E36F9701D17}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {83CE8910-37AA-415A-954B-3E36F9701D17}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {84AEBF14-8E14-414B-9266-A750D7260CC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {84AEBF14-8E14-414B-9266-A750D7260CC9}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {84AEBF14-8E14-414B-9266-A750D7260CC9}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {84AEBF14-8E14-414B-9266-A750D7260CC9}.Release|Any CPU.Build.0 = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(SolutionProperties) = preSolution 30 | HideSolutionNode = FALSE 31 | EndGlobalSection 32 | EndGlobal 33 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/Lab/SimpleDbContextStorage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Objects; 6 | using System.Data.Entity; 7 | 8 | namespace Infrastructure.Data.EntityFramework.Lab 9 | { 10 | public class SimpleDbContextStorage : IDbContextStorage 11 | { 12 | private Dictionary _storage = new Dictionary(); 13 | 14 | /// 15 | /// Initializes a new instance of the class. 16 | /// 17 | public SimpleDbContextStorage() { } 18 | 19 | /// 20 | /// Returns the db context associated with the specified key or 21 | /// null if the specified key is not found. 22 | /// 23 | /// The key. 24 | /// 25 | public DbContext GetDbContextForKey(string key) 26 | { 27 | DbContext context; 28 | if (!this._storage.TryGetValue(key, out context)) 29 | return null; 30 | return context; 31 | } 32 | 33 | 34 | /// 35 | /// Stores the db context into a dictionary using the specified key. 36 | /// If an object context already exists by the specified key, 37 | /// it gets overwritten by the new object context passed in. 38 | /// 39 | /// The key. 40 | /// The object context. 41 | public void SetDbContextForKey(string key, DbContext context) 42 | { 43 | this._storage.Add(key, context); 44 | } 45 | 46 | /// 47 | /// Returns all the values of the internal dictionary of db contexts. 48 | /// 49 | /// 50 | public IEnumerable GetAllDbContexts() 51 | { 52 | return this._storage.Values; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/SimpleObjectContextStorage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Objects; 6 | 7 | namespace Infrastructure.Data.EntityFramework 8 | { 9 | /// 10 | /// Simple object context storage implementation 11 | /// 12 | public class SimpleObjectContextStorage : IObjectContextStorage 13 | { 14 | private Dictionary storage = new Dictionary(); 15 | 16 | /// 17 | /// Initializes a new instance of the class. 18 | /// 19 | public SimpleObjectContextStorage() { } 20 | 21 | /// 22 | /// Returns the object context associated with the specified key or 23 | /// null if the specified key is not found. 24 | /// 25 | /// The key. 26 | /// 27 | public ObjectContext GetObjectContextForKey(string key) 28 | { 29 | ObjectContext context; 30 | if (!this.storage.TryGetValue(key, out context)) 31 | return null; 32 | return context; 33 | } 34 | 35 | 36 | /// 37 | /// Stores the object context into a dictionary using the specified key. 38 | /// If an object context already exists by the specified key, 39 | /// it gets overwritten by the new object context passed in. 40 | /// 41 | /// The key. 42 | /// The object context. 43 | public void SetObjectContextForKey(string key, ObjectContext objectContext) 44 | { 45 | this.storage.Add(key, objectContext); 46 | } 47 | 48 | /// 49 | /// Returns all the values of the internal dictionary of object contexts. 50 | /// 51 | /// 52 | public IEnumerable GetAllObjectContexts() 53 | { 54 | return this.storage.Values; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /net40/Infrastructure.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure.Tests", "Infrastructure.Tests\Infrastructure.Tests.csproj", "{A5158294-F45B-4073-9F56-BD263F67B336}" 5 | EndProject 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure.Model", "Infrastructure.Model\Infrastructure.Model.csproj", "{3DB01132-5E0D-46A5-8C68-E4D9C2A12D7D}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure.Data", "Infrastructure.Data\Infrastructure.Data.csproj", "{7CE588E9-6E48-43A9-843C-3078E6372255}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure.Data.EntityFramework", "Infrastructure.Data.EntityFramework\Infrastructure.Data.EntityFramework.csproj", "{B69BC712-D7B1-45A4-9C9F-682CE3A7BD8C}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {A5158294-F45B-4073-9F56-BD263F67B336}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {A5158294-F45B-4073-9F56-BD263F67B336}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {A5158294-F45B-4073-9F56-BD263F67B336}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {A5158294-F45B-4073-9F56-BD263F67B336}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {3DB01132-5E0D-46A5-8C68-E4D9C2A12D7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {3DB01132-5E0D-46A5-8C68-E4D9C2A12D7D}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {3DB01132-5E0D-46A5-8C68-E4D9C2A12D7D}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {3DB01132-5E0D-46A5-8C68-E4D9C2A12D7D}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {7CE588E9-6E48-43A9-843C-3078E6372255}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {7CE588E9-6E48-43A9-843C-3078E6372255}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {7CE588E9-6E48-43A9-843C-3078E6372255}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {7CE588E9-6E48-43A9-843C-3078E6372255}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {B69BC712-D7B1-45A4-9C9F-682CE3A7BD8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {B69BC712-D7B1-45A4-9C9F-682CE3A7BD8C}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {B69BC712-D7B1-45A4-9C9F-682CE3A7BD8C}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {B69BC712-D7B1-45A4-9C9F-682CE3A7BD8C}.Release|Any CPU.Build.0 = Release|Any CPU 34 | EndGlobalSection 35 | GlobalSection(SolutionProperties) = preSolution 36 | HideSolutionNode = FALSE 37 | EndGlobalSection 38 | EndGlobal 39 | -------------------------------------------------------------------------------- /net45/Infrastructure.Model/Infrastructure.Model.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {84AEBF14-8E14-414B-9266-A750D7260CC9} 8 | Library 9 | Properties 10 | Infrastructure.Model 11 | Infrastructure.Model 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 56 | -------------------------------------------------------------------------------- /net40/Infrastructure.Model/Infrastructure.Model.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Debug 5 | AnyCPU 6 | 8.0.30703 7 | 2.0 8 | {3DB01132-5E0D-46A5-8C68-E4D9C2A12D7D} 9 | Library 10 | Properties 11 | Infrastructure.Model 12 | Infrastructure.Model 13 | v4.0 14 | 512 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | ..\packages\EntityFramework.4.3.0\lib\net40\EntityFramework.dll 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 61 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data/Infrastructure.Data.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Debug 5 | AnyCPU 6 | 8.0.30703 7 | 2.0 8 | {7CE588E9-6E48-43A9-843C-3078E6372255} 9 | Library 10 | Properties 11 | Infrastructure.Data 12 | Infrastructure.Data 13 | v4.0 14 | 512 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 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 | 65 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/WebObjectContextStorage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Web; 6 | using System.Data.Objects; 7 | 8 | namespace Infrastructure.Data.EntityFramework 9 | { 10 | /// 11 | /// In web application, esp. MVC app, this is how an ObjectContext is initialized and stored in WebObjectContextStorage. 12 | /// This is, again, inspired from S#arp Architect code 13 | /// 14 | /// using Infrastructure.Data; 15 | /// public class MvcApplication : System.Web.HttpApplication 16 | /// { 17 | /// // other code ... 18 | /// public override void Init() 19 | /// { 20 | /// base.Init(); 21 | /// _storage = new WebObjectContextStorage(this); 22 | /// } 23 | /// 24 | /// protected void Application_BeginRequest(object sender, EventArgs e) 25 | /// { 26 | /// ObjectContextInitializer.Instance().InitializeObjectContextOnce(() => 27 | /// { 28 | /// ObjectContextManager.InitStorage(_storage); 29 | /// ObjectContextManager.Init(new[] { Server.MapPath("~/bin/mapping-assembly.dll") }); 30 | /// }); 31 | /// } 32 | /// private WebObjectContextStorage _storage; 33 | /// } 34 | /// 35 | public class WebObjectContextStorage : IObjectContextStorage 36 | { 37 | public WebObjectContextStorage(HttpApplication app) 38 | { 39 | app.EndRequest += (sender, args) => 40 | { 41 | ObjectContextManager.CloseAllObjectContexts(); 42 | HttpContext.Current.Items.Remove(HttpContextObjectContextStorageKey); 43 | }; 44 | } 45 | 46 | public ObjectContext GetObjectContextForKey(string key) 47 | { 48 | SimpleObjectContextStorage storage = GetSimpleObjectContextStorage(); 49 | return storage.GetObjectContextForKey(key); 50 | } 51 | 52 | public void SetObjectContextForKey(string factoryKey, ObjectContext session) 53 | { 54 | SimpleObjectContextStorage storage = GetSimpleObjectContextStorage(); 55 | storage.SetObjectContextForKey(factoryKey, session); 56 | } 57 | 58 | public IEnumerable GetAllObjectContexts() 59 | { 60 | SimpleObjectContextStorage storage = GetSimpleObjectContextStorage(); 61 | return storage.GetAllObjectContexts(); 62 | } 63 | 64 | private SimpleObjectContextStorage GetSimpleObjectContextStorage() 65 | { 66 | HttpContext context = HttpContext.Current; 67 | SimpleObjectContextStorage storage = context.Items[HttpContextObjectContextStorageKey] as SimpleObjectContextStorage; 68 | if (storage == null) 69 | { 70 | storage = new SimpleObjectContextStorage(); 71 | context.Items[HttpContextObjectContextStorageKey] = storage; 72 | } 73 | return storage; 74 | } 75 | 76 | private static readonly string HttpContextObjectContextStorageKey = "HttpContextObjectContextStorageKey"; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/DataSeedingInitializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Tests.Data.Domain; 6 | using System.Data.Entity; 7 | using Infrastructure.Data; 8 | 9 | namespace Infrastructure.Tests.Data 10 | { 11 | /// 12 | /// Seeding data 13 | /// 14 | public class DataSeedingInitializer : DropCreateDatabaseAlways 15 | { 16 | protected override void Seed(MyDbContext context) 17 | { 18 | CreateCustomer(context); 19 | CreateProducts(context); 20 | AddOrders(context); 21 | } 22 | 23 | private void CreateCustomer(MyDbContext context) 24 | { 25 | var c = new Customer { Firstname = "John", Lastname = "Doe", Inserted = DateTime.Now }; 26 | context.Customers.Add(c); 27 | context.SaveChanges(); 28 | } 29 | 30 | private void CreateProducts(MyDbContext context) 31 | { 32 | Category osCategory = new Category { Name = "Operating System" }; 33 | Category msProductCategory = new Category { Name = "MS Product" }; 34 | 35 | context.Categories.Add(osCategory); 36 | context.Categories.Add(msProductCategory); 37 | 38 | var p1 = new Product { Name = "Windows Seven Professional", Price = 100 }; 39 | p1.Categories.Add(osCategory); 40 | p1.Categories.Add(msProductCategory); 41 | context.Products.Add(p1); 42 | 43 | var p2 = new Product { Name = "Windows XP Professional", Price = 20 }; 44 | p2.Categories.Add(osCategory); 45 | p2.Categories.Add(msProductCategory); 46 | context.Products.Add(p2); 47 | 48 | var p3 = new Product { Name = "Windows Seven Home", Price = 80 }; 49 | p3.Categories.Add(osCategory); 50 | p3.Categories.Add(msProductCategory); 51 | context.Products.Add(p3); 52 | 53 | var p4 = new Product { Name = "Windows Seven Ultimate", Price = 110 }; 54 | p4.Categories.Add(osCategory); 55 | p4.Categories.Add(msProductCategory); 56 | context.Products.Add(p4); 57 | 58 | var p5 = new Product { Name = "Windows Seven Premium", Price = 150 }; 59 | p5.Categories.Add(osCategory); 60 | p5.Categories.Add(msProductCategory); 61 | context.Products.Add(p5); 62 | 63 | context.SaveChanges(); 64 | Console.WriteLine("Saved five Products in 2 Category"); 65 | } 66 | 67 | private void AddOrders(MyDbContext context) 68 | { 69 | var c = context.Customers.Where(x => x.Firstname == "John" && x.Lastname == "Doe").SingleOrDefault(); 70 | 71 | var winXP = context.Products.Where(x => x.Name == "Windows XP Professional").SingleOrDefault(); 72 | var winSeven = context.Products.Where(x => x.Name == "Windows Seven Professional").SingleOrDefault(); 73 | 74 | var o = new Order 75 | { 76 | OrderDate = DateTime.Now, 77 | Customer = c, 78 | OrderLines = new List 79 | { 80 | new OrderLine { Price = 200, Product = winXP, Quantity = 1}, 81 | new OrderLine { Price = 699.99, Product = winSeven, Quantity = 5 } 82 | } 83 | }; 84 | 85 | context.Orders.Add(o); 86 | context.SaveChanges(); 87 | Console.WriteLine("Saved one order"); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Lab/DataSeedingInitializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Infrastructure.Tests.Data.Domain; 6 | using System.Data.Entity; 7 | using Infrastructure.Data; 8 | 9 | namespace Infrastructure.Tests.Data.Lab 10 | { 11 | /// 12 | /// Seeding data 13 | /// 14 | public class DataSeedingInitializer : DropCreateDatabaseAlways 15 | { 16 | protected override void Seed(MyDbContext context) 17 | { 18 | CreateCustomer(context); 19 | CreateProducts(context); 20 | AddOrders(context); 21 | } 22 | 23 | private void CreateCustomer(MyDbContext context) 24 | { 25 | var c = new Customer { Firstname = "John", Lastname = "Doe", Inserted = DateTime.Now }; 26 | context.Customers.Add(c); 27 | context.SaveChanges(); 28 | } 29 | 30 | private void CreateProducts(MyDbContext context) 31 | { 32 | Category osCategory = new Category { Name = "Operating System" }; 33 | Category msProductCategory = new Category { Name = "MS Product" }; 34 | 35 | context.Categories.Add(osCategory); 36 | context.Categories.Add(msProductCategory); 37 | 38 | var p1 = new Product { Name = "Windows Seven Professional", Price = 100 }; 39 | p1.Categories.Add(osCategory); 40 | p1.Categories.Add(msProductCategory); 41 | context.Products.Add(p1); 42 | 43 | var p2 = new Product { Name = "Windows XP Professional", Price = 20 }; 44 | p2.Categories.Add(osCategory); 45 | p2.Categories.Add(msProductCategory); 46 | context.Products.Add(p2); 47 | 48 | var p3 = new Product { Name = "Windows Seven Home", Price = 80 }; 49 | p3.Categories.Add(osCategory); 50 | p3.Categories.Add(msProductCategory); 51 | context.Products.Add(p3); 52 | 53 | var p4 = new Product { Name = "Windows Seven Ultimate", Price = 110 }; 54 | p4.Categories.Add(osCategory); 55 | p4.Categories.Add(msProductCategory); 56 | context.Products.Add(p4); 57 | 58 | var p5 = new Product { Name = "Windows Seven Premium", Price = 150 }; 59 | p5.Categories.Add(osCategory); 60 | p5.Categories.Add(msProductCategory); 61 | context.Products.Add(p5); 62 | 63 | context.SaveChanges(); 64 | Console.WriteLine("Saved five Products in 2 Category"); 65 | } 66 | 67 | private void AddOrders(MyDbContext context) 68 | { 69 | var c = context.Customers.Where(x => x.Firstname == "John" && x.Lastname == "Doe").SingleOrDefault(); 70 | 71 | var winXP = context.Products.Where(x => x.Name == "Windows XP Professional").SingleOrDefault(); 72 | var winSeven = context.Products.Where(x => x.Name == "Windows Seven Professional").SingleOrDefault(); 73 | 74 | var o = new Order 75 | { 76 | OrderDate = DateTime.Now, 77 | Customer = c, 78 | OrderLines = new List 79 | { 80 | new OrderLine { Price = 200, Product = winXP, Quantity = 1}, 81 | new OrderLine { Price = 699.99, Product = winSeven, Quantity = 5 } 82 | } 83 | }; 84 | 85 | context.Orders.Add(o); 86 | context.SaveChanges(); 87 | Console.WriteLine("Saved one order"); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/Infrastructure.Data.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {83CE8910-37AA-415A-954B-3E36F9701D17} 8 | Library 9 | Properties 10 | Infrastructure.Data 11 | Infrastructure.Data 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 81 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/Infrastructure.Data.EntityFramework.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Debug 5 | AnyCPU 6 | 8.0.30703 7 | 2.0 8 | {B69BC712-D7B1-45A4-9C9F-682CE3A7BD8C} 9 | Library 10 | Properties 11 | Infrastructure.Data.EntityFramework 12 | Infrastructure.Data.EntityFramework 13 | v4.0 14 | 512 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | ..\packages\EntityFramework.4.3.0\lib\net40\EntityFramework.dll 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | Code 55 | 56 | 57 | Code 58 | 59 | 60 | Code 61 | 62 | 63 | Code 64 | 65 | 66 | Code 67 | 68 | 69 | Code 70 | 71 | 72 | Code 73 | 74 | 75 | Code 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | {7CE588E9-6E48-43A9-843C-3078E6372255} 88 | Infrastructure.Data 89 | 90 | 91 | 92 | 93 | 94 | 95 | 102 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/UnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Objects; 3 | using System.Data; 4 | using System.Data.Common; 5 | using System.Data.Entity; 6 | using System.Data.Entity.Infrastructure; 7 | 8 | namespace Infrastructure.Data 9 | { 10 | internal class UnitOfWork : IUnitOfWork 11 | { 12 | private DbTransaction _transaction; 13 | private DbContext _dbContext; 14 | 15 | public UnitOfWork(DbContext context) 16 | { 17 | _dbContext = context; 18 | } 19 | 20 | public bool IsInTransaction 21 | { 22 | get { return _transaction != null; } 23 | } 24 | 25 | public void BeginTransaction() 26 | { 27 | BeginTransaction(IsolationLevel.ReadCommitted); 28 | } 29 | 30 | public void BeginTransaction(IsolationLevel isolationLevel) 31 | { 32 | if (_transaction != null) 33 | { 34 | throw new ApplicationException("Cannot begin a new transaction while an existing transaction is still running. " + 35 | "Please commit or rollback the existing transaction before starting a new one."); 36 | } 37 | OpenConnection(); 38 | _transaction = ((IObjectContextAdapter)_dbContext).ObjectContext.Connection.BeginTransaction(isolationLevel); 39 | } 40 | 41 | public void RollBackTransaction() 42 | { 43 | if (_transaction == null) 44 | { 45 | throw new ApplicationException("Cannot roll back a transaction while there is no transaction running."); 46 | } 47 | 48 | if (IsInTransaction) 49 | { 50 | _transaction.Rollback(); 51 | ReleaseCurrentTransaction(); 52 | } 53 | } 54 | 55 | public void CommitTransaction() 56 | { 57 | if (_transaction == null) 58 | { 59 | throw new ApplicationException("Cannot roll back a transaction while there is no transaction running."); 60 | } 61 | 62 | try 63 | { 64 | ((IObjectContextAdapter)_dbContext).ObjectContext.SaveChanges(); 65 | _transaction.Commit(); 66 | ReleaseCurrentTransaction(); 67 | } 68 | catch 69 | { 70 | RollBackTransaction(); 71 | throw; 72 | } 73 | } 74 | 75 | public void SaveChanges() 76 | { 77 | if (IsInTransaction) 78 | { 79 | throw new ApplicationException("A transaction is running. Call CommitTransaction instead."); 80 | } 81 | ((IObjectContextAdapter)_dbContext).ObjectContext.SaveChanges(); 82 | } 83 | 84 | public void SaveChanges(SaveOptions saveOptions) 85 | { 86 | if (IsInTransaction) 87 | { 88 | throw new ApplicationException("A transaction is running. Call CommitTransaction instead."); 89 | } 90 | 91 | ((IObjectContextAdapter)_dbContext).ObjectContext.SaveChanges(saveOptions); 92 | } 93 | 94 | #region Implementation of IDisposable 95 | 96 | /// 97 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. 98 | /// 99 | public void Dispose() 100 | { 101 | Dispose(true); 102 | GC.SuppressFinalize(this); 103 | } 104 | 105 | /// 106 | /// Disposes off the managed and unmanaged resources used. 107 | /// 108 | /// 109 | private void Dispose(bool disposing) 110 | { 111 | if (!disposing) 112 | return; 113 | 114 | if (_disposed) 115 | return; 116 | 117 | _disposed = true; 118 | } 119 | 120 | private bool _disposed; 121 | #endregion 122 | 123 | private void OpenConnection() 124 | { 125 | if (((IObjectContextAdapter)_dbContext).ObjectContext.Connection.State != ConnectionState.Open) 126 | { 127 | ((IObjectContextAdapter)_dbContext).ObjectContext.Connection.Open(); 128 | } 129 | } 130 | 131 | /// 132 | /// Releases the current transaction 133 | /// 134 | private void ReleaseCurrentTransaction() 135 | { 136 | if (_transaction != null) 137 | { 138 | _transaction.Dispose(); 139 | _transaction = null; 140 | } 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/UnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Objects; 6 | using System.Data; 7 | using System.Data.Common; 8 | 9 | namespace Infrastructure.Data.EntityFramework 10 | { 11 | internal class UnitOfWork : IUnitOfWork 12 | { 13 | private DbTransaction _transaction; 14 | private ObjectContext _objectContext; 15 | 16 | public UnitOfWork(ObjectContext context) 17 | { 18 | _objectContext = context; 19 | } 20 | 21 | public bool IsInTransaction 22 | { 23 | get { return _transaction != null; } 24 | } 25 | 26 | public void BeginTransaction() 27 | { 28 | BeginTransaction(IsolationLevel.ReadCommitted); 29 | } 30 | 31 | public void BeginTransaction(IsolationLevel isolationLevel) 32 | { 33 | if (_transaction != null) 34 | { 35 | throw new ApplicationException("Cannot begin a new transaction while an existing transaction is still running. " + 36 | "Please commit or rollback the existing transaction before starting a new one."); 37 | } 38 | OpenConnection(); 39 | _transaction = _objectContext.Connection.BeginTransaction(isolationLevel); 40 | } 41 | 42 | public void RollBackTransaction() 43 | { 44 | if (_transaction == null) 45 | { 46 | throw new ApplicationException("Cannot roll back a transaction while there is no transaction running."); 47 | } 48 | 49 | if (IsInTransaction) 50 | { 51 | _transaction.Rollback(); 52 | ReleaseCurrentTransaction(); 53 | } 54 | } 55 | 56 | public void CommitTransaction() 57 | { 58 | if (_transaction == null) 59 | { 60 | throw new ApplicationException("Cannot roll back a transaction while there is no transaction running."); 61 | } 62 | 63 | try 64 | { 65 | _objectContext.SaveChanges(); 66 | _transaction.Commit(); 67 | ReleaseCurrentTransaction(); 68 | } 69 | catch 70 | { 71 | RollBackTransaction(); 72 | throw; 73 | } 74 | } 75 | 76 | public void SaveChanges() 77 | { 78 | if (IsInTransaction) 79 | { 80 | throw new ApplicationException("A transaction is running. Call CommitTransaction instead."); 81 | } 82 | _objectContext.SaveChanges(); 83 | } 84 | 85 | /// 86 | /// Save temporary change with transaction 87 | /// 88 | public void Save() 89 | { 90 | if (!IsInTransaction) 91 | throw new ApplicationException("No transaction is running. Please call BeginTransaction first."); 92 | _objectContext.SaveChanges(); 93 | } 94 | 95 | /// 96 | /// Directly save change without using begin transaction with saving option 97 | /// 98 | public void Save(SaveOptions saveOptions) 99 | { 100 | if (!IsInTransaction) 101 | throw new ApplicationException("No transaction is running. Please call BeginTransaction first."); 102 | 103 | _objectContext.SaveChanges(saveOptions); 104 | } 105 | 106 | public void SaveChanges(SaveOptions saveOptions) 107 | { 108 | if (IsInTransaction) 109 | { 110 | throw new ApplicationException("A transaction is running. Call BeginTransaction instead."); 111 | } 112 | _objectContext.SaveChanges(saveOptions); 113 | } 114 | 115 | /// 116 | /// Releases the current transaction 117 | /// 118 | private void ReleaseCurrentTransaction() 119 | { 120 | if (_transaction != null) 121 | { 122 | _transaction.Dispose(); 123 | _transaction = null; 124 | } 125 | } 126 | 127 | private void OpenConnection() 128 | { 129 | if (_objectContext.Connection.State != ConnectionState.Open) 130 | { 131 | _objectContext.Connection.Open(); 132 | } 133 | } 134 | 135 | #region Implementation of IDisposable 136 | 137 | /// 138 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. 139 | /// 140 | public void Dispose() 141 | { 142 | Dispose(true); 143 | GC.SuppressFinalize(this); 144 | } 145 | 146 | /// 147 | /// Disposes the managed and unmanaged resources. 148 | /// 149 | /// 150 | private void Dispose(bool disposing) 151 | { 152 | if (!disposing) 153 | return; 154 | 155 | if (_disposed) 156 | return; 157 | 158 | ReleaseCurrentTransaction(); 159 | 160 | _disposed = true; 161 | } 162 | private bool _disposed; 163 | #endregion 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Infrastructure.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Debug 5 | AnyCPU 6 | 8.0.30703 7 | 2.0 8 | {A5158294-F45B-4073-9F56-BD263F67B336} 9 | Library 10 | Properties 11 | Infrastructure.Tests 12 | Infrastructure.Tests 13 | v4.0 14 | 512 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | ..\packages\EntityFramework.4.3.0\lib\net40\EntityFramework.dll 36 | 37 | 38 | False 39 | ..\packages\NUnit\nunit.framework.dll 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | Code 57 | 58 | 59 | 60 | 61 | Code 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | Code 75 | 76 | 77 | Code 78 | 79 | 80 | Code 81 | 82 | 83 | Code 84 | 85 | 86 | Code 87 | 88 | 89 | 90 | 91 | 92 | Designer 93 | 94 | 95 | 96 | 97 | 98 | {B69BC712-D7B1-45A4-9C9F-682CE3A7BD8C} 99 | Infrastructure.Data.EntityFramework 100 | 101 | 102 | {7CE588E9-6E48-43A9-843C-3078E6372255} 103 | Infrastructure.Data 104 | 105 | 106 | {3DB01132-5E0D-46A5-8C68-E4D9C2A12D7D} 107 | Infrastructure.Model 108 | 109 | 110 | 111 | 118 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/Lab/UnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Objects; 3 | using System.Data; 4 | using System.Data.Common; 5 | using System.Data.Entity; 6 | using System.Data.Entity.Infrastructure; 7 | 8 | namespace Infrastructure.Data.EntityFramework.Lab 9 | { 10 | internal class UnitOfWork : IUnitOfWork 11 | { 12 | private DbTransaction _transaction; 13 | private DbContext _dbContext; 14 | 15 | public UnitOfWork(DbContext context) 16 | { 17 | _dbContext = context; 18 | } 19 | 20 | public bool IsInTransaction 21 | { 22 | get { return _transaction != null; } 23 | } 24 | 25 | public void BeginTransaction() 26 | { 27 | BeginTransaction(IsolationLevel.ReadCommitted); 28 | } 29 | 30 | public void BeginTransaction(IsolationLevel isolationLevel) 31 | { 32 | if (_transaction != null) 33 | { 34 | throw new ApplicationException("Cannot begin a new transaction while an existing transaction is still running. " + 35 | "Please commit or rollback the existing transaction before starting a new one."); 36 | } 37 | OpenConnection(); 38 | _transaction = ((IObjectContextAdapter)_dbContext).ObjectContext.Connection.BeginTransaction(isolationLevel); 39 | } 40 | 41 | public void RollBackTransaction() 42 | { 43 | if (_transaction == null) 44 | { 45 | throw new ApplicationException("Cannot roll back a transaction while there is no transaction running."); 46 | } 47 | 48 | if (IsInTransaction) 49 | { 50 | _transaction.Rollback(); 51 | ReleaseCurrentTransaction(); 52 | } 53 | } 54 | 55 | public void CommitTransaction() 56 | { 57 | if (_transaction == null) 58 | { 59 | throw new ApplicationException("Cannot roll back a transaction while there is no transaction running."); 60 | } 61 | 62 | try 63 | { 64 | ((IObjectContextAdapter)_dbContext).ObjectContext.SaveChanges(); 65 | _transaction.Commit(); 66 | ReleaseCurrentTransaction(); 67 | } 68 | catch 69 | { 70 | RollBackTransaction(); 71 | throw; 72 | } 73 | } 74 | 75 | /// 76 | /// Directly save change without using begin transaction 77 | /// 78 | public void SaveChanges() 79 | { 80 | if (IsInTransaction) 81 | { 82 | throw new ApplicationException("A transaction is running. Call CommitTransaction instead."); 83 | } 84 | ((IObjectContextAdapter)_dbContext).ObjectContext.SaveChanges(); 85 | } 86 | 87 | /// 88 | /// Save temporary change with transaction 89 | /// 90 | public void Save() 91 | { 92 | if (!IsInTransaction) 93 | throw new ApplicationException("No transaction is running. Please call BeginTransaction first."); 94 | ((IObjectContextAdapter)_dbContext).ObjectContext.SaveChanges(); 95 | } 96 | 97 | /// 98 | /// Directly save change without using begin transaction with saving option 99 | /// 100 | public void Save(SaveOptions saveOptions) 101 | { 102 | if (!IsInTransaction) 103 | throw new ApplicationException("No transaction is running. Please call BeginTransaction first."); 104 | 105 | ((IObjectContextAdapter)_dbContext).ObjectContext.SaveChanges(saveOptions); 106 | } 107 | 108 | /// 109 | /// Directly save change without using begin transaction with saving option 110 | /// 111 | public void SaveChanges(SaveOptions saveOptions) 112 | { 113 | if (IsInTransaction) 114 | { 115 | throw new ApplicationException("A transaction is running. Call CommitTransaction instead."); 116 | } 117 | 118 | ((IObjectContextAdapter)_dbContext).ObjectContext.SaveChanges(saveOptions); 119 | } 120 | 121 | #region Implementation of IDisposable 122 | 123 | /// 124 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. 125 | /// 126 | public void Dispose() 127 | { 128 | Dispose(true); 129 | GC.SuppressFinalize(this); 130 | } 131 | 132 | /// 133 | /// Disposes off the managed and unmanaged resources used. 134 | /// 135 | /// 136 | private void Dispose(bool disposing) 137 | { 138 | if (!disposing) 139 | return; 140 | 141 | if (_disposed) 142 | return; 143 | 144 | _disposed = true; 145 | } 146 | 147 | private bool _disposed; 148 | #endregion 149 | 150 | private void OpenConnection() 151 | { 152 | if (((IObjectContextAdapter)_dbContext).ObjectContext.Connection.State != ConnectionState.Open) 153 | { 154 | ((IObjectContextAdapter)_dbContext).ObjectContext.Connection.Open(); 155 | } 156 | } 157 | 158 | /// 159 | /// Releases the current transaction 160 | /// 161 | private void ReleaseCurrentTransaction() 162 | { 163 | if (_transaction != null) 164 | { 165 | _transaction.Dispose(); 166 | _transaction = null; 167 | } 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/DbContextBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Configuration; 2 | using System.Data.Common; 3 | using System.Data.Objects; 4 | using System; 5 | using System.Reflection; 6 | using System.Data.Entity.ModelConfiguration; 7 | using System.Data.Entity; 8 | using System.Data.Entity.Infrastructure; 9 | 10 | namespace Infrastructure.Data 11 | { 12 | public interface IDbContextBuilder where T : DbContext 13 | { 14 | T BuildDbContext(); 15 | } 16 | 17 | public class DbContextBuilder : DbModelBuilder, IDbContextBuilder where T : DbContext 18 | { 19 | private readonly DbProviderFactory _factory; 20 | private readonly ConnectionStringSettings _cnStringSettings; 21 | private readonly bool _recreateDatabaseIfExists; 22 | private readonly bool _lazyLoadingEnabled; 23 | 24 | public DbContextBuilder(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExists, bool lazyLoadingEnabled) 25 | { 26 | _cnStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName]; 27 | _factory = DbProviderFactories.GetFactory(_cnStringSettings.ProviderName); 28 | _recreateDatabaseIfExists = recreateDatabaseIfExists; 29 | _lazyLoadingEnabled = lazyLoadingEnabled; 30 | 31 | AddConfigurations(mappingAssemblies); 32 | } 33 | 34 | /// 35 | /// Creates a new . 36 | /// 37 | /// if set to true [lazy loading enabled]. 38 | /// if set to true [recreate database if exist]. 39 | /// 40 | public T BuildDbContext() 41 | { 42 | var cn = _factory.CreateConnection(); 43 | cn.ConnectionString = _cnStringSettings.ConnectionString; 44 | 45 | var dbModel = this.Build(cn); 46 | 47 | ObjectContext ctx = dbModel.Compile().CreateObjectContext(cn); 48 | ctx.ContextOptions.LazyLoadingEnabled = this._lazyLoadingEnabled; 49 | 50 | if (!ctx.DatabaseExists()) 51 | { 52 | ctx.CreateDatabase(); 53 | } 54 | else if (_recreateDatabaseIfExists) 55 | { 56 | ctx.DeleteDatabase(); 57 | ctx.CreateDatabase(); 58 | } 59 | 60 | return (T)new DbContext(ctx, true); 61 | } 62 | 63 | /// 64 | /// Adds mapping classes contained in provided assemblies and register entities as well 65 | /// 66 | /// 67 | private void AddConfigurations(string[] mappingAssemblies) 68 | { 69 | if (mappingAssemblies == null || mappingAssemblies.Length == 0) 70 | { 71 | throw new ArgumentNullException("mappingAssemblies", "You must specify at least one mapping assembly"); 72 | } 73 | 74 | bool hasMappingClass = false; 75 | foreach (string mappingAssembly in mappingAssemblies) 76 | { 77 | Assembly asm = Assembly.LoadFrom(MakeLoadReadyAssemblyName(mappingAssembly)); 78 | 79 | foreach (Type type in asm.GetTypes()) 80 | { 81 | if (!type.IsAbstract) 82 | { 83 | if (type.BaseType.IsGenericType && IsMappingClass(type.BaseType)) 84 | { 85 | hasMappingClass = true; 86 | 87 | // http://areaofinterest.wordpress.com/2010/12/08/dynamically-load-entity-configurations-in-ef-codefirst-ctp5/ 88 | dynamic configurationInstance = Activator.CreateInstance(type); 89 | this.Configurations.Add(configurationInstance); 90 | } 91 | } 92 | } 93 | } 94 | 95 | if (!hasMappingClass) 96 | { 97 | throw new ArgumentException("No mapping class found!"); 98 | } 99 | } 100 | 101 | /// 102 | /// Determines whether a type is a subclass of entity mapping type 103 | /// 104 | /// Type of the mapping. 105 | /// 106 | /// true if it is mapping class; otherwise, false. 107 | /// 108 | private bool IsMappingClass(Type mappingType) 109 | { 110 | Type baseType = typeof(EntityTypeConfiguration<>); 111 | if (mappingType.GetGenericTypeDefinition() == baseType) 112 | { 113 | return true; 114 | } 115 | if ((mappingType.BaseType != null) && 116 | !mappingType.BaseType.IsAbstract && 117 | mappingType.BaseType.IsGenericType) 118 | { 119 | return IsMappingClass(mappingType.BaseType); 120 | } 121 | return false; 122 | } 123 | 124 | /// 125 | /// Ensures the assembly name is qualified 126 | /// 127 | /// 128 | /// 129 | private static string MakeLoadReadyAssemblyName(string assemblyName) 130 | { 131 | return (assemblyName.IndexOf(".dll") == -1) 132 | ? assemblyName.Trim() + ".dll" 133 | : assemblyName.Trim(); 134 | } 135 | 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/ObjectContextBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Configuration; 2 | using System.Data.Common; 3 | using System.Data.Entity.Design.PluralizationServices; 4 | using System.Data.Objects; 5 | using System.Globalization; 6 | using System; 7 | using System.Reflection; 8 | using System.Data.Entity.ModelConfiguration; 9 | using System.Data.Entity; 10 | using System.Data.Entity.Infrastructure; 11 | 12 | namespace Infrastructure.Data.EntityFramework 13 | { 14 | public interface IObjectContextBuilder where T : ObjectContext 15 | { 16 | T BuildObjectContext(); 17 | } 18 | 19 | public class ObjectContextBuilder : DbModelBuilder, IObjectContextBuilder where T : ObjectContext 20 | { 21 | private readonly DbProviderFactory _factory; 22 | private readonly ConnectionStringSettings _cnStringSettings; 23 | private readonly bool _recreateDatabaseIfExists; 24 | private readonly bool _lazyLoadingEnabled; 25 | 26 | public ObjectContextBuilder(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExists, bool lazyLoadingEnabled) 27 | { 28 | this.Conventions.Remove(); 29 | 30 | _cnStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName]; 31 | _factory = DbProviderFactories.GetFactory(_cnStringSettings.ProviderName); 32 | _recreateDatabaseIfExists = recreateDatabaseIfExists; 33 | _lazyLoadingEnabled = lazyLoadingEnabled; 34 | 35 | AddConfigurations(mappingAssemblies); 36 | } 37 | 38 | /// 39 | /// Creates a new . 40 | /// 41 | /// if set to true [lazy loading enabled]. 42 | /// if set to true [recreate database if exist]. 43 | /// 44 | public T BuildObjectContext() 45 | { 46 | var cn = _factory.CreateConnection(); 47 | cn.ConnectionString = _cnStringSettings.ConnectionString; 48 | 49 | var dbModel = this.Build(cn); 50 | 51 | ObjectContext ctx = dbModel.Compile().CreateObjectContext(cn); 52 | ctx.ContextOptions.LazyLoadingEnabled = this._lazyLoadingEnabled; 53 | 54 | if (!ctx.DatabaseExists()) 55 | { 56 | ctx.CreateDatabase(); 57 | } 58 | else if (_recreateDatabaseIfExists) 59 | { 60 | ctx.DeleteDatabase(); 61 | ctx.CreateDatabase(); 62 | } 63 | 64 | return (T)ctx; 65 | } 66 | 67 | /// 68 | /// Adds mapping classes contained in provided assemblies and register entities as well 69 | /// 70 | /// 71 | private void AddConfigurations(string[] mappingAssemblies) 72 | { 73 | if (mappingAssemblies == null || mappingAssemblies.Length == 0) 74 | { 75 | throw new ArgumentNullException("mappingAssemblies", "You must specify at least one mapping assembly"); 76 | } 77 | 78 | bool hasMappingClass = false; 79 | foreach (string mappingAssembly in mappingAssemblies) 80 | { 81 | Assembly asm = Assembly.LoadFrom(MakeLoadReadyAssemblyName(mappingAssembly)); 82 | 83 | foreach (Type type in asm.GetTypes()) 84 | { 85 | if (!type.IsAbstract) 86 | { 87 | if (type.BaseType.IsGenericType && IsMappingClass(type.BaseType)) 88 | { 89 | hasMappingClass = true; 90 | 91 | // http://areaofinterest.wordpress.com/2010/12/08/dynamically-load-entity-configurations-in-ef-codefirst-ctp5/ 92 | dynamic configurationInstance = Activator.CreateInstance(type); 93 | this.Configurations.Add(configurationInstance); 94 | } 95 | } 96 | } 97 | } 98 | 99 | if (!hasMappingClass) 100 | { 101 | throw new ArgumentException("No mapping class found!"); 102 | } 103 | } 104 | 105 | /// 106 | /// Determines whether a type is a subclass of entity mapping type 107 | /// 108 | /// Type of the mapping. 109 | /// 110 | /// true if it is mapping class; otherwise, false. 111 | /// 112 | private bool IsMappingClass(Type mappingType) 113 | { 114 | Type baseType = typeof(EntityTypeConfiguration<>); 115 | if (mappingType.GetGenericTypeDefinition() == baseType) 116 | { 117 | return true; 118 | } 119 | if ((mappingType.BaseType != null) && 120 | !mappingType.BaseType.IsAbstract && 121 | mappingType.BaseType.IsGenericType) 122 | { 123 | return IsMappingClass(mappingType.BaseType); 124 | } 125 | return false; 126 | } 127 | 128 | /// 129 | /// Ensures the assembly name is qualified 130 | /// 131 | /// 132 | /// 133 | private static string MakeLoadReadyAssemblyName(string assemblyName) 134 | { 135 | return (assemblyName.IndexOf(".dll") == -1) 136 | ? assemblyName.Trim() + ".dll" 137 | : assemblyName.Trim(); 138 | } 139 | } 140 | } -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/Lab/DbContextBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Configuration; 2 | using System.Data.Common; 3 | using System.Data.Entity.Design.PluralizationServices; 4 | using System.Data.Objects; 5 | using System.Globalization; 6 | using System; 7 | using System.Reflection; 8 | using System.Data.Entity.ModelConfiguration; 9 | using System.Data.Entity; 10 | using System.Data.Entity.Infrastructure; 11 | 12 | namespace Infrastructure.Data.EntityFramework.Lab 13 | { 14 | public interface IDbContextBuilder where T : DbContext 15 | { 16 | T BuildDbContext(); 17 | } 18 | 19 | public class DbContextBuilder : DbModelBuilder, IDbContextBuilder where T : DbContext 20 | { 21 | private readonly DbProviderFactory _factory; 22 | private readonly ConnectionStringSettings _cnStringSettings; 23 | private readonly bool _recreateDatabaseIfExists; 24 | private readonly bool _lazyLoadingEnabled; 25 | 26 | public DbContextBuilder(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExists, bool lazyLoadingEnabled) 27 | { 28 | this.Conventions.Remove(); 29 | 30 | _cnStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName]; 31 | _factory = DbProviderFactories.GetFactory(_cnStringSettings.ProviderName); 32 | _recreateDatabaseIfExists = recreateDatabaseIfExists; 33 | _lazyLoadingEnabled = lazyLoadingEnabled; 34 | 35 | AddConfigurations(mappingAssemblies); 36 | } 37 | 38 | /// 39 | /// Creates a new . 40 | /// 41 | /// if set to true [lazy loading enabled]. 42 | /// if set to true [recreate database if exist]. 43 | /// 44 | public T BuildDbContext() 45 | { 46 | var cn = _factory.CreateConnection(); 47 | cn.ConnectionString = _cnStringSettings.ConnectionString; 48 | 49 | var dbModel = this.Build(cn); 50 | 51 | ObjectContext ctx = dbModel.Compile().CreateObjectContext(cn); 52 | ctx.ContextOptions.LazyLoadingEnabled = this._lazyLoadingEnabled; 53 | 54 | if (!ctx.DatabaseExists()) 55 | { 56 | ctx.CreateDatabase(); 57 | } 58 | else if (_recreateDatabaseIfExists) 59 | { 60 | ctx.DeleteDatabase(); 61 | ctx.CreateDatabase(); 62 | } 63 | 64 | return (T)new DbContext(ctx, true); 65 | } 66 | 67 | /// 68 | /// Adds mapping classes contained in provided assemblies and register entities as well 69 | /// 70 | /// 71 | private void AddConfigurations(string[] mappingAssemblies) 72 | { 73 | if (mappingAssemblies == null || mappingAssemblies.Length == 0) 74 | { 75 | throw new ArgumentNullException("mappingAssemblies", "You must specify at least one mapping assembly"); 76 | } 77 | 78 | bool hasMappingClass = false; 79 | foreach (string mappingAssembly in mappingAssemblies) 80 | { 81 | Assembly asm = Assembly.LoadFrom(MakeLoadReadyAssemblyName(mappingAssembly)); 82 | 83 | foreach (Type type in asm.GetTypes()) 84 | { 85 | if (!type.IsAbstract) 86 | { 87 | if (type.BaseType.IsGenericType && IsMappingClass(type.BaseType)) 88 | { 89 | hasMappingClass = true; 90 | 91 | // http://areaofinterest.wordpress.com/2010/12/08/dynamically-load-entity-configurations-in-ef-codefirst-ctp5/ 92 | dynamic configurationInstance = Activator.CreateInstance(type); 93 | this.Configurations.Add(configurationInstance); 94 | } 95 | } 96 | } 97 | } 98 | 99 | if (!hasMappingClass) 100 | { 101 | throw new ArgumentException("No mapping class found!"); 102 | } 103 | } 104 | 105 | /// 106 | /// Determines whether a type is a subclass of entity mapping type 107 | /// 108 | /// Type of the mapping. 109 | /// 110 | /// true if it is mapping class; otherwise, false. 111 | /// 112 | private bool IsMappingClass(Type mappingType) 113 | { 114 | Type baseType = typeof(EntityTypeConfiguration<>); 115 | if (mappingType.GetGenericTypeDefinition() == baseType) 116 | { 117 | return true; 118 | } 119 | if ((mappingType.BaseType != null) && 120 | !mappingType.BaseType.IsAbstract && 121 | mappingType.BaseType.IsGenericType) 122 | { 123 | return IsMappingClass(mappingType.BaseType); 124 | } 125 | return false; 126 | } 127 | 128 | /// 129 | /// Ensures the assembly name is qualified 130 | /// 131 | /// 132 | /// 133 | private static string MakeLoadReadyAssemblyName(string assemblyName) 134 | { 135 | return (assemblyName.IndexOf(".dll") == -1) 136 | ? assemblyName.Trim() + ".dll" 137 | : assemblyName.Trim(); 138 | } 139 | 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /net45/Infrastructure.Data/DbContextManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data.Entity; 4 | using System.Data.Entity.Infrastructure; 5 | 6 | namespace Infrastructure.Data 7 | { 8 | public class DbContextManager 9 | { 10 | public static void Init(string[] mappingAssemblies, bool recreateDatabaseIfExist = false, bool lazyLoadingEnabled = true) 11 | { 12 | Init(DefaultConnectionStringName, mappingAssemblies, recreateDatabaseIfExist, lazyLoadingEnabled); 13 | } 14 | 15 | public static void Init(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExist = false, bool lazyLoadingEnabled = true) 16 | { 17 | AddConfiguration(connectionStringName, mappingAssemblies, recreateDatabaseIfExist, lazyLoadingEnabled); 18 | } 19 | 20 | public static void InitStorage(IDbContextStorage storage) 21 | { 22 | if (storage == null) 23 | { 24 | throw new ArgumentNullException("storage"); 25 | } 26 | if ((_storage != null) && (_storage != storage)) 27 | { 28 | throw new ApplicationException("A storage mechanism has already been configured for this application"); 29 | } 30 | _storage = storage; 31 | } 32 | 33 | /// 34 | /// The default connection string name used if only one database is being communicated with. 35 | /// 36 | public static readonly string DefaultConnectionStringName = "DefaultDb"; 37 | 38 | /// 39 | /// Used to get the current db context session if you're communicating with a single database. 40 | /// When communicating with multiple databases, invoke instead. 41 | /// 42 | public static DbContext Current 43 | { 44 | get 45 | { 46 | return CurrentFor(DefaultConnectionStringName); 47 | } 48 | } 49 | 50 | /// 51 | /// Used to get the current DbContext associated with a key; i.e., the key 52 | /// associated with an object context for a specific database. 53 | /// 54 | /// If you're only communicating with one database, you should call instead, 55 | /// although you're certainly welcome to call this if you have the key available. 56 | /// 57 | public static DbContext CurrentFor(string key) 58 | { 59 | if (string.IsNullOrEmpty(key)) 60 | { 61 | throw new ArgumentNullException("key"); 62 | } 63 | 64 | if (_storage == null) 65 | { 66 | throw new ApplicationException("An IDbContextStorage has not been initialized"); 67 | } 68 | 69 | DbContext context = null; 70 | lock (_syncLock) 71 | { 72 | if (!_dbContextBuilders.ContainsKey(key)) 73 | { 74 | throw new ApplicationException("An DbContextBuilder does not exist with a key of " + key); 75 | } 76 | 77 | context = _storage.GetDbContextForKey(key); 78 | 79 | if (context == null) 80 | { 81 | context = _dbContextBuilders[key].BuildDbContext(); 82 | _storage.SetDbContextForKey(key, context); 83 | } 84 | } 85 | return context; 86 | } 87 | 88 | /// 89 | /// This method is used by application-specific db context storage implementations 90 | /// and unit tests. Its job is to walk thru existing cached object context(s) and Close() each one. 91 | /// 92 | public static void CloseAllDbContexts() 93 | { 94 | foreach (DbContext ctx in _storage.GetAllDbContexts()) 95 | { 96 | if (((IObjectContextAdapter)ctx).ObjectContext.Connection.State == System.Data.ConnectionState.Open) 97 | ((IObjectContextAdapter)ctx).ObjectContext.Connection.Close(); 98 | } 99 | } 100 | 101 | private static void AddConfiguration(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExists = false, bool lazyLoadingEnabled = true) 102 | { 103 | if (string.IsNullOrEmpty(connectionStringName)) 104 | { 105 | throw new ArgumentNullException("connectionStringName"); 106 | } 107 | 108 | if (mappingAssemblies == null) 109 | { 110 | throw new ArgumentNullException("mappingAssemblies"); 111 | } 112 | 113 | lock (_syncLock) 114 | { 115 | _dbContextBuilders.Add(connectionStringName, 116 | new DbContextBuilder(connectionStringName, mappingAssemblies, recreateDatabaseIfExists, lazyLoadingEnabled)); 117 | } 118 | } 119 | 120 | /// 121 | /// An application-specific implementation of IDbContextStorage must be setup either thru 122 | /// or one of the overloads. 123 | /// 124 | private static IDbContextStorage _storage { get; set; } 125 | 126 | /// 127 | /// Maintains a dictionary of db context builders, one per database. The key is a 128 | /// connection string name used to look up the associated database, and used to decorate respective 129 | /// repositories. If only one database is being used, this dictionary contains a single 130 | /// factory with a key of . 131 | /// 132 | private static Dictionary> _dbContextBuilders = new Dictionary>(); 133 | 134 | private static object _syncLock = new object(); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/ObjectContextManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Objects; 6 | 7 | namespace Infrastructure.Data.EntityFramework 8 | { 9 | public static class ObjectContextManager 10 | { 11 | public static void Init(string[] mappingAssemblies, bool recreateDatabaseIfExist = false, bool lazyLoadingEnabled = true) 12 | { 13 | Init(DefaultConnectionStringName, mappingAssemblies, recreateDatabaseIfExist, lazyLoadingEnabled); 14 | } 15 | 16 | public static void Init(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExist = false, bool lazyLoadingEnabled = true) 17 | { 18 | AddConfiguration(connectionStringName, mappingAssemblies, recreateDatabaseIfExist, lazyLoadingEnabled); 19 | } 20 | 21 | public static void InitStorage(IObjectContextStorage storage) 22 | { 23 | if (storage == null) 24 | { 25 | throw new ArgumentNullException("storage"); 26 | } 27 | if ((Storage != null) && (Storage != storage)) 28 | { 29 | throw new ApplicationException("A storage mechanism has already been configured for this application"); 30 | } 31 | Storage = storage; 32 | } 33 | 34 | /// 35 | /// The default connection string name used if only one database is being communicated with. 36 | /// 37 | public static readonly string DefaultConnectionStringName = "DefaultDb"; 38 | 39 | /// 40 | /// Used to get the current object context session if you're communicating with a single database. 41 | /// When communicating with multiple databases, invoke instead. 42 | /// 43 | public static ObjectContext Current 44 | { 45 | get 46 | { 47 | return CurrentFor(DefaultConnectionStringName); 48 | } 49 | } 50 | 51 | /// 52 | /// Used to get the current ObjectContext associated with a key; i.e., the key 53 | /// associated with an object context for a specific database. 54 | /// 55 | /// If you're only communicating with one database, you should call instead, 56 | /// although you're certainly welcome to call this if you have the key available. 57 | /// 58 | public static ObjectContext CurrentFor(string key) 59 | { 60 | if (string.IsNullOrEmpty(key)) 61 | { 62 | throw new ArgumentNullException("key"); 63 | } 64 | 65 | if (Storage == null) 66 | { 67 | throw new ApplicationException("An IObjectContextStorage has not been initialized"); 68 | } 69 | 70 | ObjectContext context = null; 71 | lock (_syncLock) 72 | { 73 | if (!objectContextBuilders.ContainsKey(key)) 74 | { 75 | throw new ApplicationException("An ObjectContextBuilder does not exist with a key of " + key); 76 | } 77 | 78 | context = Storage.GetObjectContextForKey(key); 79 | 80 | if (context == null) 81 | { 82 | context = objectContextBuilders[key].BuildObjectContext(); 83 | Storage.SetObjectContextForKey(key, context); 84 | } 85 | } 86 | 87 | return context; 88 | } 89 | 90 | /// 91 | /// This method is used by application-specific object context storage implementations 92 | /// and unit tests. Its job is to walk thru existing cached object context(s) and Close() each one. 93 | /// 94 | public static void CloseAllObjectContexts() 95 | { 96 | foreach (ObjectContext ctx in Storage.GetAllObjectContexts()) 97 | { 98 | if (ctx.Connection.State == System.Data.ConnectionState.Open) 99 | ctx.Connection.Close(); 100 | } 101 | } 102 | 103 | private static void AddConfiguration(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExists = false, bool lazyLoadingEnabled = true) 104 | { 105 | if (string.IsNullOrEmpty(connectionStringName)) 106 | { 107 | throw new ArgumentNullException("connectionStringName"); 108 | } 109 | 110 | if (mappingAssemblies == null) 111 | { 112 | throw new ArgumentNullException("mappingAssemblies"); 113 | } 114 | 115 | objectContextBuilders.Add(connectionStringName, 116 | new ObjectContextBuilder(connectionStringName, mappingAssemblies, recreateDatabaseIfExists, lazyLoadingEnabled)); 117 | } 118 | 119 | /// 120 | /// An application-specific implementation of IObjectContextStorage must be setup either thru 121 | /// or one of the overloads. 122 | /// 123 | private static IObjectContextStorage Storage { get; set; } 124 | 125 | /// 126 | /// Maintains a dictionary of object context builders, one per database. The key is a 127 | /// connection string name used to look up the associated database, and used to decorate respective 128 | /// repositories. If only one database is being used, this dictionary contains a single 129 | /// factory with a key of . 130 | /// 131 | private static Dictionary> objectContextBuilders = new Dictionary>(); 132 | 133 | private static object _syncLock = new object(); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /net40/Infrastructure.Data.EntityFramework/Lab/DbContextManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data.Objects; 6 | using System.Data.Entity; 7 | using System.Data.Entity.Infrastructure; 8 | 9 | namespace Infrastructure.Data.EntityFramework.Lab 10 | { 11 | public class DbContextManager 12 | { 13 | public static void Init(string[] mappingAssemblies, bool recreateDatabaseIfExist = false, bool lazyLoadingEnabled = true) 14 | { 15 | Init(DefaultConnectionStringName, mappingAssemblies, recreateDatabaseIfExist, lazyLoadingEnabled); 16 | } 17 | 18 | public static void Init(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExist = false, bool lazyLoadingEnabled = true) 19 | { 20 | AddConfiguration(connectionStringName, mappingAssemblies, recreateDatabaseIfExist, lazyLoadingEnabled); 21 | } 22 | 23 | public static void InitStorage(IDbContextStorage storage) 24 | { 25 | if (storage == null) 26 | { 27 | throw new ArgumentNullException("storage"); 28 | } 29 | if ((_storage != null) && (_storage != storage)) 30 | { 31 | throw new ApplicationException("A storage mechanism has already been configured for this application"); 32 | } 33 | _storage = storage; 34 | } 35 | 36 | /// 37 | /// The default connection string name used if only one database is being communicated with. 38 | /// 39 | public static readonly string DefaultConnectionStringName = "DefaultDb"; 40 | 41 | /// 42 | /// Used to get the current db context session if you're communicating with a single database. 43 | /// When communicating with multiple databases, invoke instead. 44 | /// 45 | public static DbContext Current 46 | { 47 | get 48 | { 49 | return CurrentFor(DefaultConnectionStringName); 50 | } 51 | } 52 | 53 | /// 54 | /// Used to get the current DbContext associated with a key; i.e., the key 55 | /// associated with an object context for a specific database. 56 | /// 57 | /// If you're only communicating with one database, you should call instead, 58 | /// although you're certainly welcome to call this if you have the key available. 59 | /// 60 | public static DbContext CurrentFor(string key) 61 | { 62 | if (string.IsNullOrEmpty(key)) 63 | { 64 | throw new ArgumentNullException("key"); 65 | } 66 | 67 | if (_storage == null) 68 | { 69 | throw new ApplicationException("An IDbContextStorage has not been initialized"); 70 | } 71 | 72 | DbContext context = null; 73 | lock (_syncLock) 74 | { 75 | if (!_dbContextBuilders.ContainsKey(key)) 76 | { 77 | throw new ApplicationException("An DbContextBuilder does not exist with a key of " + key); 78 | } 79 | 80 | context = _storage.GetDbContextForKey(key); 81 | 82 | if (context == null) 83 | { 84 | context = _dbContextBuilders[key].BuildDbContext(); 85 | _storage.SetDbContextForKey(key, context); 86 | } 87 | } 88 | return context; 89 | } 90 | 91 | /// 92 | /// This method is used by application-specific db context storage implementations 93 | /// and unit tests. Its job is to walk thru existing cached object context(s) and Close() each one. 94 | /// 95 | public static void CloseAllDbContexts() 96 | { 97 | foreach (DbContext ctx in _storage.GetAllDbContexts()) 98 | { 99 | if (((IObjectContextAdapter)ctx).ObjectContext.Connection.State == System.Data.ConnectionState.Open) 100 | ((IObjectContextAdapter)ctx).ObjectContext.Connection.Close(); 101 | } 102 | } 103 | 104 | private static void AddConfiguration(string connectionStringName, string[] mappingAssemblies, bool recreateDatabaseIfExists = false, bool lazyLoadingEnabled = true) 105 | { 106 | if (string.IsNullOrEmpty(connectionStringName)) 107 | { 108 | throw new ArgumentNullException("connectionStringName"); 109 | } 110 | 111 | if (mappingAssemblies == null) 112 | { 113 | throw new ArgumentNullException("mappingAssemblies"); 114 | } 115 | 116 | lock (_syncLock) 117 | { 118 | _dbContextBuilders.Add(connectionStringName, 119 | new DbContextBuilder(connectionStringName, mappingAssemblies, recreateDatabaseIfExists, lazyLoadingEnabled)); 120 | } 121 | } 122 | 123 | /// 124 | /// An application-specific implementation of IDbContextStorage must be setup either thru 125 | /// or one of the overloads. 126 | /// 127 | private static IDbContextStorage _storage { get; set; } 128 | 129 | /// 130 | /// Maintains a dictionary of db context builders, one per database. The key is a 131 | /// connection string name used to look up the associated database, and used to decorate respective 132 | /// repositories. If only one database is being used, this dictionary contains a single 133 | /// factory with a key of . 134 | /// 135 | private static Dictionary> _dbContextBuilders = new Dictionary>(); 136 | 137 | private static object _syncLock = new object(); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Infrastructure.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Debug 5 | AnyCPU 6 | {4083B654-9EBA-416D-B5D1-27EBA222B831} 7 | Library 8 | Properties 9 | Infrastructure.Tests 10 | Infrastructure.Tests 11 | v4.5 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\EntityFramework.5.0.0\lib\net45\EntityFramework.dll 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | {83ce8910-37aa-415a-954b-3e36f9701d17} 82 | Infrastructure.Data 83 | 84 | 85 | {84aebf14-8e14-414b-9266-a750d7260cc9} 86 | Infrastructure.Model 87 | 88 | 89 | 90 | 91 | Designer 92 | 93 | 94 | 95 | 96 | 97 | 98 | False 99 | 100 | 101 | False 102 | 103 | 104 | False 105 | 106 | 107 | False 108 | 109 | 110 | 111 | 112 | 113 | 114 | 121 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/UseMyDbContextTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using Infrastructure.Tests.Data.Domain; 6 | using Infrastructure.Data.Specification; 7 | using Infrastructure.Tests.Data.Specification; 8 | using Infrastructure.Data; 9 | using System.Data.Entity; 10 | using System.Data.Entity.Infrastructure; 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | namespace Infrastructure.Tests.Data 14 | { 15 | [TestClass] 16 | public class UseMyDbContextTest 17 | { 18 | private ICustomerRepository customerRepository; 19 | private IRepository repository; 20 | private MyDbContext context; 21 | 22 | [TestInitialize] 23 | public void SetUp() 24 | { 25 | Database.SetInitializer(new DataSeedingInitializer()); 26 | context = new MyDbContext("DefaultDb"); 27 | 28 | customerRepository = new CustomerRepository(context); 29 | repository = new GenericRepository(context); 30 | } 31 | 32 | [TestMethod] 33 | public void GenerateDatabaseScriptTest() 34 | { 35 | string script = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript(); 36 | // for debugging 37 | Console.WriteLine(script); 38 | Assert.IsTrue(!string.IsNullOrEmpty(script)); 39 | } 40 | 41 | [TestCleanup] 42 | public void TearDown() 43 | { 44 | if ((context != null) && (((IObjectContextAdapter)context).ObjectContext.Connection.State == System.Data.ConnectionState.Open)) 45 | { 46 | ((IObjectContextAdapter)context).ObjectContext.Connection.Close(); 47 | context = null; 48 | } 49 | } 50 | 51 | [TestMethod] 52 | public void Test() 53 | { 54 | DoAction(() => FindOneCustomer()); 55 | DoAction(() => FindCategoryWithInclude()); 56 | DoAction(() => FindManyOrdersForJohnDoe()); 57 | DoAction(() => FindNewlySubscribed()); 58 | DoAction(() => FindBySpecification()); 59 | DoAction(() => FindByCompositeSpecification()); 60 | DoAction(() => FindByConcretSpecification()); 61 | DoAction(() => FindByConcretCompositeSpecification()); 62 | DoAction(() => UpdateProduct()); 63 | } 64 | 65 | private void FindCategoryWithInclude() 66 | { 67 | var category = repository.GetQuery(x => x.Name == "Operating System").Include(c => c.Products).SingleOrDefault(); 68 | Assert.IsNotNull(category); 69 | Assert.IsTrue(category.Products.Count > 0); 70 | } 71 | 72 | private void FindManyOrdersForJohnDoe() 73 | { 74 | var customer = customerRepository.FindByName("John", "Doe"); 75 | var orders = repository.Find(x => x.Customer.Id == customer.Id); 76 | 77 | Console.Write("Found {0} Orders with {1} OrderLines", orders.Count(), orders.ToList()[0].OrderLines.Count); 78 | } 79 | 80 | private void FindNewlySubscribed() 81 | { 82 | var newCustomers = customerRepository.NewlySubscribed(); 83 | 84 | Console.Write("Found {0} new customers", newCustomers.Count); 85 | } 86 | 87 | private void FindBySpecification() 88 | { 89 | Specification specification = new Specification(p => p.Price < 100); 90 | IEnumerable productsOnSale = repository.Find(specification); 91 | Assert.AreEqual(2, productsOnSale.Count()); 92 | } 93 | 94 | private void FindByCompositeSpecification() 95 | { 96 | IEnumerable products = repository.Find( 97 | new Specification(p => p.Price < 100).And(new Specification(p => p.Name == "Windows XP Professional"))); 98 | Assert.AreEqual(1, products.Count()); 99 | } 100 | 101 | private void FindByConcretSpecification() 102 | { 103 | ProductOnSaleSpecification specification = new ProductOnSaleSpecification(); 104 | IEnumerable productsOnSale = repository.Find(specification); 105 | Assert.AreEqual(2, productsOnSale.Count()); 106 | } 107 | 108 | private void FindByConcretCompositeSpecification() 109 | { 110 | IEnumerable products = repository.Find( 111 | new AndSpecification( 112 | new ProductOnSaleSpecification(), 113 | new ProductByNameSpecification("Windows XP Professional"))); 114 | Assert.AreEqual(1, products.Count()); 115 | } 116 | 117 | private void FindOneCustomer() 118 | { 119 | var c = repository.FindOne(x => x.Firstname == "John" && 120 | x.Lastname == "Doe"); 121 | 122 | Console.Write("Found Customer: {0} {1}", c.Firstname, c.Lastname); 123 | } 124 | 125 | private void GetProductsWithPaging() 126 | { 127 | var output = repository.Get(x => x.Name, 0, 5).ToList(); 128 | Assert.IsTrue(output[0].Name == "Windows Seven Home"); 129 | Assert.IsTrue(output[1].Name == "Windows Seven Premium"); 130 | Assert.IsTrue(output[2].Name == "Windows Seven Professional"); 131 | Assert.IsTrue(output[3].Name == "Windows Seven Ultimate"); 132 | Assert.IsTrue(output[4].Name == "Windows XP Professional"); 133 | } 134 | 135 | private void UpdateProduct() 136 | { 137 | repository.UnitOfWork.BeginTransaction(); 138 | 139 | var output = repository.FindOne(x => x.Name == "Windows XP Professional"); 140 | Assert.IsNotNull(output); 141 | 142 | output.Name = "Windows XP Home"; 143 | repository.Update(output); 144 | repository.UnitOfWork.CommitTransaction(); 145 | 146 | var updated = repository.FindOne(x => x.Name == "Windows XP Home"); 147 | Assert.IsNotNull(updated); 148 | } 149 | 150 | private static void DoAction(Expression action) 151 | { 152 | Console.Write("Executing {0} ... ", action.Body.ToString()); 153 | 154 | var act = action.Compile(); 155 | act.Invoke(); 156 | 157 | Console.WriteLine(); 158 | } 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /net40/Infrastructure.Tests/Data/Lab/UseMyDbContextTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using NUnit.Framework; 5 | using System.Linq.Expressions; 6 | using Infrastructure.Tests.Data.Domain; 7 | using Infrastructure.Data.Specification; 8 | using Infrastructure.Tests.Data.Specification; 9 | using Infrastructure.Data; 10 | using Infrastructure.Data.EntityFramework.Lab; 11 | using System.Data; 12 | using System.Data.Entity; 13 | using Infrastructure.Tests.Data.Domain.Mapping; 14 | using System.Data.Entity.Infrastructure; 15 | 16 | namespace Infrastructure.Tests.Data.Lab 17 | { 18 | [TestFixture] 19 | public class UseMyDbContextTest 20 | { 21 | private Infrastructure.Tests.Data.Lab.ICustomerRepository customerRepository; 22 | private IRepository repository; 23 | private MyDbContext context; 24 | 25 | [TestFixtureSetUp] 26 | public void SetUp() 27 | { 28 | Database.SetInitializer(new DataSeedingInitializer()); 29 | context = new MyDbContext("DefaultDb"); 30 | 31 | customerRepository = new Infrastructure.Tests.Data.Lab.CustomerRepository(context); 32 | repository = new Infrastructure.Data.EntityFramework.Lab.GenericRepository(context); 33 | } 34 | 35 | [Test] 36 | public void GenerateDatabaseScriptTest() 37 | { 38 | string script = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript(); 39 | // for debugging 40 | Console.WriteLine(script); 41 | Assert.IsNotNullOrEmpty(script); 42 | } 43 | 44 | [TestFixtureTearDown] 45 | public void TearDown() 46 | { 47 | if ((context != null) && (((IObjectContextAdapter)context).ObjectContext.Connection.State == System.Data.ConnectionState.Open)) 48 | { 49 | ((IObjectContextAdapter)context).ObjectContext.Connection.Close(); 50 | context = null; 51 | } 52 | } 53 | 54 | [Test] 55 | public void Test() 56 | { 57 | DoAction(() => FindOneCustomer()); 58 | DoAction(() => FindCategoryWithInclude()); 59 | DoAction(() => FindManyOrdersForJohnDoe()); 60 | DoAction(() => FindNewlySubscribed()); 61 | DoAction(() => FindBySpecification()); 62 | DoAction(() => FindByCompositeSpecification()); 63 | DoAction(() => FindByConcretSpecification()); 64 | DoAction(() => FindByConcretCompositeSpecification()); 65 | DoAction(() => UpdateProduct()); 66 | } 67 | 68 | private void FindCategoryWithInclude() 69 | { 70 | var category = repository.GetQuery(x => x.Name == "Operating System").Include(c => c.Products).SingleOrDefault(); 71 | Assert.IsNotNull(category); 72 | Assert.Greater(category.Products.Count, 0); 73 | } 74 | 75 | private void FindManyOrdersForJohnDoe() 76 | { 77 | var customer = customerRepository.FindByName("John", "Doe"); 78 | var orders = repository.Find(x => x.Customer.Id == customer.Id); 79 | 80 | Console.Write("Found {0} Orders with {1} OrderLines", orders.Count(), orders.ToList()[0].OrderLines.Count); 81 | } 82 | 83 | private void FindNewlySubscribed() 84 | { 85 | var newCustomers = customerRepository.NewlySubscribed(); 86 | 87 | Console.Write("Found {0} new customers", newCustomers.Count); 88 | } 89 | 90 | private void FindBySpecification() 91 | { 92 | Specification specification = new Specification(p => p.Price < 100); 93 | IEnumerable productsOnSale = repository.Find(specification); 94 | Assert.AreEqual(2, productsOnSale.Count()); 95 | } 96 | 97 | private void FindByCompositeSpecification() 98 | { 99 | IEnumerable products = repository.Find( 100 | new Specification(p => p.Price < 100).And(new Specification(p => p.Name == "Windows XP Professional"))); 101 | Assert.AreEqual(1, products.Count()); 102 | } 103 | 104 | private void FindByConcretSpecification() 105 | { 106 | ProductOnSaleSpecification specification = new ProductOnSaleSpecification(); 107 | IEnumerable productsOnSale = repository.Find(specification); 108 | Assert.AreEqual(2, productsOnSale.Count()); 109 | } 110 | 111 | private void FindByConcretCompositeSpecification() 112 | { 113 | IEnumerable products = repository.Find( 114 | new AndSpecification( 115 | new ProductOnSaleSpecification(), 116 | new ProductByNameSpecification("Windows XP Professional"))); 117 | Assert.AreEqual(1, products.Count()); 118 | } 119 | 120 | private void FindOneCustomer() 121 | { 122 | var c = repository.FindOne(x => x.Firstname == "John" && 123 | x.Lastname == "Doe"); 124 | 125 | Console.Write("Found Customer: {0} {1}", c.Firstname, c.Lastname); 126 | } 127 | 128 | private void GetProductsWithPaging() 129 | { 130 | var output = repository.Get(x => x.Name, 0, 5).ToList(); 131 | Assert.IsTrue(output[0].Name == "Windows Seven Home"); 132 | Assert.IsTrue(output[1].Name == "Windows Seven Premium"); 133 | Assert.IsTrue(output[2].Name == "Windows Seven Professional"); 134 | Assert.IsTrue(output[3].Name == "Windows Seven Ultimate"); 135 | Assert.IsTrue(output[4].Name == "Windows XP Professional"); 136 | } 137 | 138 | private void UpdateProduct() 139 | { 140 | repository.UnitOfWork.BeginTransaction(); 141 | 142 | var output = repository.FindOne(x => x.Name == "Windows XP Professional"); 143 | Assert.IsNotNull(output); 144 | 145 | output.Name = "Windows XP Home"; 146 | repository.Update(output); 147 | repository.UnitOfWork.CommitTransaction(); 148 | 149 | var updated = repository.FindOne(x => x.Name == "Windows XP Home"); 150 | Assert.IsNotNull(updated); 151 | } 152 | 153 | private static void DoAction(Expression action) 154 | { 155 | Console.Write("Executing {0} ... ", action.Body.ToString()); 156 | 157 | var act = action.Compile(); 158 | act.Invoke(); 159 | 160 | Console.WriteLine(); 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /net45/Infrastructure.Tests/Data/RepositoryTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Data.Entity; 5 | using System.Linq.Expressions; 6 | using Infrastructure.Tests.Data.Domain; 7 | using Infrastructure.Data.Specification; 8 | using Infrastructure.Tests.Data.Specification; 9 | using Infrastructure.Data; 10 | using Microsoft.VisualStudio.TestTools.UnitTesting; 11 | 12 | namespace Infrastructure.Tests.Data 13 | { 14 | /// 15 | /// This class is used to test the _lab_ version of repository implementation 16 | /// 17 | [TestClass] 18 | public class RepositoryTest 19 | { 20 | private ICustomerRepository customerRepository; 21 | private IRepository repository; 22 | 23 | [TestInitialize] 24 | public void SetUp() 25 | { 26 | DbContextManager.InitStorage(new SimpleDbContextStorage()); 27 | DbContextManager.Init("DefaultDb", new[] { "Infrastructure.Tests" }, true); 28 | 29 | customerRepository = new CustomerRepository(); 30 | repository = new GenericRepository(); 31 | } 32 | 33 | [TestCleanup] 34 | public void TearDown() 35 | { 36 | DbContextManager.CloseAllDbContexts(); 37 | } 38 | 39 | [TestMethod] 40 | public void Test() 41 | { 42 | DoAction(() => CreateCustomer()); 43 | DoAction(() => CreateProducts()); 44 | DoAction(() => AddOrders()); 45 | DoAction(() => FindOneCustomer()); 46 | DoAction(() => FindByKey()); 47 | DoAction(() => FindManyOrdersForJohnDoe()); 48 | DoAction(() => FindNewlySubscribed()); 49 | DoAction(() => FindOrderWithInclude()); 50 | DoAction(() => FindBySpecification()); 51 | DoAction(() => FindByCompositeSpecification()); 52 | DoAction(() => FindByConcretSpecification()); 53 | DoAction(() => FindByConcretCompositeSpecification()); 54 | DoAction(() => FindByChainOfSpecifications()); 55 | } 56 | 57 | private void FindBySpecification() 58 | { 59 | Specification specification = new Specification(p => p.Price < 100); 60 | IEnumerable productsOnSale = repository.Find(specification); 61 | Assert.AreEqual(2, productsOnSale.Count()); 62 | } 63 | 64 | private void FindByCompositeSpecification() 65 | { 66 | IEnumerable products = repository.Find( 67 | new Specification(p => p.Price < 100).And(new Specification(p => p.Name == "Windows XP Professional"))); 68 | Assert.AreEqual(1, products.Count()); 69 | } 70 | 71 | private void FindByConcretSpecification() 72 | { 73 | ProductOnSaleSpecification specification = new ProductOnSaleSpecification(); 74 | IEnumerable productsOnSale = repository.Find(specification); 75 | Assert.AreEqual(2, productsOnSale.Count()); 76 | } 77 | 78 | private void FindByConcretCompositeSpecification() 79 | { 80 | IEnumerable products = repository.Find( 81 | new AndSpecification( 82 | new ProductOnSaleSpecification(), 83 | new ProductByNameSpecification("Windows XP Professional"))); 84 | Assert.AreEqual(1, products.Count()); 85 | } 86 | 87 | private void FindByChainOfSpecifications() 88 | { 89 | IEnumerable products = repository.Find( 90 | new ProductOnSaleSpecification() 91 | .And(new ProductByNameSpecification("Windows XP Professional"))); 92 | Assert.AreEqual(1, products.Count()); 93 | } 94 | 95 | private void FindOrderWithInclude() 96 | { 97 | var c = customerRepository.FindByName("John", "Doe"); 98 | List orders = repository.Find(x => x.Customer.Id == c.Id).ToList(); 99 | Console.Write("Found {0} Orders with {1} OrderLines", orders.Count(), orders.ToList()[0].OrderLines.Count); 100 | } 101 | 102 | private void CreateProducts() 103 | { 104 | Category osCategory = new Category { Name = "Operating System" }; 105 | Category msProductCategory = new Category { Name = "MS Product" }; 106 | 107 | repository.Add(osCategory); 108 | repository.Add(msProductCategory); 109 | 110 | var p1 = new Product { Name = "Windows Seven Professional", Price = 100 }; 111 | p1.Categories.Add(osCategory); 112 | p1.Categories.Add(msProductCategory); 113 | repository.Add(p1); 114 | 115 | var p2 = new Product { Name = "Windows XP Professional", Price = 20 }; 116 | p2.Categories.Add(osCategory); 117 | p2.Categories.Add(msProductCategory); 118 | repository.Add(p2); 119 | 120 | var p3 = new Product { Name = "Windows Seven Home", Price = 80 }; 121 | p3.Categories.Add(osCategory); 122 | p3.Categories.Add(msProductCategory); 123 | repository.Add(p3); 124 | 125 | var p4 = new Product { Name = "Windows Seven Ultimate", Price = 110 }; 126 | p4.Categories.Add(osCategory); 127 | p4.Categories.Add(msProductCategory); 128 | repository.Add(p4); 129 | 130 | var p5 = new Product { Name = "Windows Seven Premium", Price = 150 }; 131 | p5.Categories.Add(osCategory); 132 | p5.Categories.Add(msProductCategory); 133 | repository.Add(p5); 134 | 135 | repository.UnitOfWork.SaveChanges(); 136 | 137 | Console.Write("Saved five Products in 2 Category"); 138 | } 139 | 140 | private void FindManyOrdersForJohnDoe() 141 | { 142 | var c = customerRepository.FindByName("John", "Doe"); 143 | var orders = repository.Find(x => x.Customer.Id == c.Id); 144 | 145 | Console.Write("Found {0} Orders with {1} OrderLines", orders.Count(), orders.ToList()[0].OrderLines.Count); 146 | } 147 | 148 | private void FindNewlySubscribed() 149 | { 150 | var newCustomers = customerRepository.NewlySubscribed(); 151 | 152 | Console.Write("Found {0} new customers", newCustomers.Count); 153 | } 154 | 155 | private void AddOrders() 156 | { 157 | var c = customerRepository.FindByName("John", "Doe"); 158 | 159 | var winXP = repository.FindOne(x => x.Name == "Windows XP Professional"); 160 | var winSeven = repository.FindOne(x => x.Name == "Windows Seven Professional"); 161 | 162 | var o = new Order 163 | { 164 | OrderDate = DateTime.Now, 165 | Customer = c, 166 | OrderLines = new List 167 | { 168 | new OrderLine { Price = 200, Product = winXP, Quantity = 1}, 169 | new OrderLine { Price = 699.99, Product = winSeven, Quantity = 5 } 170 | } 171 | }; 172 | 173 | repository.Add(o); 174 | repository.UnitOfWork.SaveChanges(); 175 | Console.Write("Saved one order"); 176 | } 177 | 178 | private void FindByKey() 179 | { 180 | var c = customerRepository.FindByName("John", "Doe"); 181 | 182 | var customer = customerRepository.GetByKey(c.Id); 183 | 184 | Console.Write("Found Customer by its PK: {0}", customer != null); 185 | } 186 | 187 | private void CreateCustomer() 188 | { 189 | var c = new Customer { Firstname = "John", Lastname = "Doe", Inserted = DateTime.Now }; 190 | customerRepository.Add(c); 191 | 192 | customerRepository.UnitOfWork.SaveChanges(); 193 | } 194 | 195 | private void FindOneCustomer() 196 | { 197 | var c = repository.FindOne(x => x.Firstname == "John" && 198 | x.Lastname == "Doe"); 199 | 200 | Console.Write("Found Customer: {0} {1}", c.Firstname, c.Lastname); 201 | } 202 | 203 | private void GetProductsWithPaging() 204 | { 205 | var output = repository.Get(x => x.Name, 0, 5).ToList(); 206 | Assert.IsTrue(output[0].Name == "Windows Seven Home"); 207 | Assert.IsTrue(output[1].Name == "Windows Seven Premium"); 208 | Assert.IsTrue(output[2].Name == "Windows Seven Professional"); 209 | Assert.IsTrue(output[3].Name == "Windows Seven Ultimate"); 210 | Assert.IsTrue(output[4].Name == "Windows XP Professional"); 211 | } 212 | 213 | private void FindCategoryWithInclude() 214 | { 215 | var category = repository.GetQuery(x => x.Name == "Operating System").Include(c => c.Products).SingleOrDefault(); 216 | Assert.IsNotNull(category); 217 | Assert.IsTrue(category.Products.Count > 0); 218 | } 219 | 220 | private static void DoAction(Expression action) 221 | { 222 | Console.Write("Executing {0} ... ", action.Body.ToString()); 223 | 224 | var act = action.Compile(); 225 | act.Invoke(); 226 | 227 | Console.WriteLine(); 228 | } 229 | } 230 | } 231 | --------------------------------------------------------------------------------