Helping Entity Framework v4.0 play it’s <ROLE> – Part 3.0
In part 1.0 we laid the foundation and part 2.0 unravelled some of the internal details of how NFetchSpec (the libraries that are subject of this discussion) goes about enlisting the benefits that can be derived by using explicit roles in your system by collapsing a swathe of Entity Framework functionality into a somewhat compact approach to dealing with a Domain Model. First a quick recap of the underpinnings.
Figure 1.0
Code from Figure 1.0
public void resolves_everything_from_container() { IList<IRunOutDiscountForProducts> products = null; var compParams = new Dictionary<string, string>(); compParams.Add(_conParamName, _connectionStringOnly); var repo = FetchSpec.Configure .With(new IoC()) .AndBuildSession<IRunOutDiscountForProducts> (compParams) .ForRepository(); using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = SessionBuilder<IRunOutDiscountForProducts>.ScopeIsolation() })) { products = repo.Get<IRunOutDiscountForProducts>(); foreach (var product in products) { product.DiscountProductForRunOut(); } scope.Complete(); } }
Figure 1.0 demonstrates how all the moving parts in the developer experience are put to use when using the NFetchSpec libraries to query and make changes to a persisted Domain Model. Let’s now examine in detail all the steps that make up the entire developer experience of composing all the discrete pieces needed in addressing the role of IRunOutDiscountForProducts (in our fictitious system).
The Development Scenario
The first outlined section in figure 1.0 demonstrates the building of an appropriate ObjectContext for the Repository that is instantiated by the fluent interface. From the developer experience perspective, nothing special needs to be done outside of specifying the role to the fluent interface in this manner.
The second outlined section in figure 1.0 highlights how the role is leveraged to dynamically have NFetchSpec chose the ‘right’ isolation level. Being explicit in this way we can achieve a high degree of separation of concerns with respect to transaction isolation and thus exercise our control over the concurrency and throughput in the database on a role by role basis. In the example, we are discounting products earmarked for a run out sale, consequently changing their unit price, therefore we might like to choose a higher isolation level for that particular operation, depending on the volatility of the data that your dealing with and the normalization or lack thereof in your database schema. For the developer this means creating a concrete implementation of the interface IProvideIsolationLevelFor<T>, to support this automagic behaviour.
public interface IProvideIsolationLevelFor<TRole> { IsolationLevel GetScopeIsolationForRole { get;} } public class RunoutDiscountIsolation : IProvideIsolationLevelFor<IRunOutDiscountForProducts> { public IsolationLevel GetScopeIsolationForRole { get { return IsolationLevel.ReadCommitted; } } }
That’s it as far as getting your transaction set for the right Isolation Level within the scope of work for a given role. If we decide at some point that this Isolation Level is not the best fit, we can replace it with a new implementation.
The Third outlined section in figure 1.0 highlights the use of the Repository to retrieve the Entities that we are interested in. This is where the NFetchSpec machinery goes to work to resolve all the purpose built artefacts that have been implemented for the given role, such as any applicative Fetching Strategy, Specification, Entity and Mapping.
The Loaded Fetching Strategy
public class ProductRunOutFetchingStrategy : FetchingStrategy<IRunOutDiscountForProducts> { public ProductRunOutFetchingStrategy() : base(false) { var production_intentions = EagerFetchingIntention .CreateInstance<IRunOutDiscountForProducts, ISupplier>(p => p.Supplier); this.AddIntentions(new IEagerFetchingIntention[] { production_intentions }); } }
The intent of the developer in building this Fetching Strategy is to load Products eagerly with their reference Supplier.
The Loaded Specification
public class RunOutProductDiscountSpecification : Specification<IRunOutDiscountForProducts> { public RunOutProductDiscountSpecification() : base(p => p.UnitPrice > 5M) { } }
The Specification is really quite simple and self evident – setting up the applicative Expression that will ultimately be translated into a ‘where’ predicate.
The Loaded Mapping
First up we need to map our Entities and that requires a Mapping<T>.
public class ProductMapping : Mapping<Product> { public ProductMapping(string objectSetName) : base(objectSetName) { Property(p => p.ProductID).IsIdentity(); Property(p => p.ProductName).HasMaxLength(50).IsRequired(); Property(p => p.UnitPrice).Precision = 19; Property(p => p.UnitPrice).Scale = 4; Relationship(p => p.Supplier).IsOptional(); Relationship(p => p.Supplier).IsOptional().FromProperty(s => s.Products); } }
And because our example has a reference Entity in the root we require the following Supplier Entity Mapping also.
public class SupplierMapping : Mapping<Supplier> { public SupplierMapping(string objectSetName) : base(objectSetName) { Property(s => s.SupplierID).IsIdentity(); Property(s => s.CompanyName).HasMaxLength(40).IsRequired(); Property(s => s.Region).HasMaxLength(15); Relationship(s => s.Products).IsOptional().FromProperty(p => p.Supplier); } }
The last requirement of the developer with respect to mapping is to create a MappingRole<T>, the purpose of which is to indicate to the infrastructure which mappings are applicable to the Role.
public class RunOutDiscountMappingRole : IMappingRole<IRunOutDiscountForProducts> { private IMapping[] _mappings; public RunOutDiscountMappingRole() { _mappings = new IMapping[] { new ProductMapping("Products"), new SupplierMapping("Suppliers") }; } public IMapping[] Mappings { get { return _mappings; } } }
The fourth and final outlined section in figure 1.0 is really the essence of what is going on here, it is entirely the reason this code is being invoked – it is the purpose (discounting products) of the system for this role. When developing in this way we need to specify the behaviour of the Role through the stable abstraction of it’s interface, and implement that behaviour in a concrete Entity.
public interface IRunOutDiscountForProducts : IProductData
{
void DiscountProductForRunOut();
}
The Bang and Crash
So with all that done, we need to deploy our “Role inspired” artefacts to the executing processes assemblies folder and when it’s all said and done the code from Figure 1.0 executes, enlisting the service of NFetchSpec in applying the combined intent and customised behaviours described in all of the deployed pieces.
From the database perspective, SQL Profiler tells us that our intent for this ROLE has been met and the system has behaved precisely as expected.
SELECT [Extent1].[ProductID] AS [ProductID], [Extent1].[ProductName] AS [ProductName], [Extent1].[UnitPrice] AS [UnitPrice], [Extent2].[CompanyName] AS [CompanyName], [Extent2].[Region] AS [Region], [Extent2].[SupplierID] AS [SupplierID] FROM [dbo].[Products] AS [Extent1] LEFT OUTER JOIN [dbo].[Suppliers] AS [Extent2] ON [Extent1].[SupplierID] = [Extent2].[SupplierID] WHERE [Extent1].[UnitPrice] > cast(5 as decimal(18))
|
UPDATE: 14th March 2010 The query above was pasted in error previously. The current text for the TSQL here is correct as of the date listed here in this update. |
We can see that Fetching Strategy and Specification have been successful in shaping the TSQL sent to the server to retrieve the data. Below we can also see the effect of applying the business rules through our Domain Model.
exec sp_executesql N‘update [dbo].[Products] set [UnitPrice] = @0 where ([ProductID] = @1) ‘,N‘@0 decimal(19,4),@1 int’,@0=3.2960,@1=1
Just one more thing
Part 4.0 will be the final part in the series and will focus on how this approach blends into a service layer in a Service Oriented Architecture and also make the code for NFetchSpec available for download.


