Houston DNUG Presentation

9. September 2011

Great crowd at the Houston DNUG tonight!! Over 110 in attendance.

Great Questions from the group during the talk. I especially like the follow ups. Thank you all for attending. Below is a link to the code you saw tonight.

http://db.tt/oJFvvrf

Here are those EF links

http://archive.msdn.microsoft.com/EFExtensions

http://www.codeproject.com/KB/database/CodeFirstStoredProcedures.aspx

For everyone interested in how to specify unique constraints that are not keys, please check this out.

http://stackoverflow.com/questions/4413084/unique-constraint-in-entity-framework-code-first

This is very similar to how we talked about adding cascade delete to foreign keys.

Thanks again, look forward to seeing you all at Houston TechFest!

Entity Framework, Community, Data Access

Reverse Engineer Code First–Jump start for existing Databases

30. May 2011

I know that we have all hit that point where we are going into a project, it has existing database structure and some old ADO.NET hand built data access layer. We think maybe this would be a great place for Entity Framework, and then we find that the business objects are serialized over WCF, or that they are somehow used in a way that makes standard EF cry. This is where we have that internal debate on if our boss will accept a week of writing code just to get code first running, not to solving the problem. In comes the EF Power Toys.

 

Just start up a new project in Visual Studio.

image

With nuget type Install-Package EntityFramework ( this avoids a bug later )

Right click the project and select Entity Framework Reverse Engineer Code first

image 

Punch in your connection information

image

Then watch the bottom left side status messages, it will load schema information, create objects and configuration for them.

You should now have a context, an entities folder, and a mappings folder.

image

This includes every entity in the database and a mapping for every property. It doesn’t leave off properties that could have taken advantage of convention.

You can use this the same way you used a code first context before.

Enjoy.

Data Access, Entity Framework, Productivity, Visual Studio 2010

Using Fluent Configuration with Entity Framework 4.1

24. May 2011

I have gotten the question several time over the last few weeks and usages for the fluent configuration of Code First POCO classes where the database does not match the convention. Here is a simple example on how to address this.

Take a product for example.

public class Product
   {
       public int ID { get; set; }
       public string Name { get; set; }
       public string ProductNumber { get; set; }
       public bool MakeFlag { get; set; }
   }

To configure this to use different column names for the properties you simply need to add a configuration for that class like so.

public class ProductConfiguration : EntityTypeConfiguration<Product>
   {
       public ProductConfiguration()
       {
           this.ToTable("Product","Production");
           this.HasKey(x => x.ID);
           this.Property(x => x.ID).HasColumnName("ProductID");
       }
   }

Notice how the inheritance tells it which class it is setting up a type configuration for.

Then you load the configuration to the context in an override like so.

public class AdventureWorkContext : DbContext
    {
        public AdventureWorkContext(string adventureWorks)
            : base(adventureWorks)
        {
            this.Database.CompatibleWithModel(false);
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new ProductConfiguration());
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Product> Products { get; set; }

}

Entity Framework, Data Access

Entity Framework–Metadata Connection Strings for EDMX files in another assembly

6. May 2011

I am sure that we have all looked at the generated EDMX files with some architectural concerns. This is probably due to the business objects and the context being tightly coupled. I have other blogs for separating this out but once you do you end up with the need to have this metadata embedded connection string for the Entites to function. This string can be placed in the app or web config and you are off the the races but what happens when your EDMX is in another assembly that lives under a different namespace and you get the dreaded “Cannot locate metadata resource specified” error? You solve it be giving a connection string that points to the location of the file. Like so.

 

public static class EntityFrameworkConnectionStringHelper
    {
        public static string GetSqlConnectionString(string serverName, string databaseName)
        {
            var providerCs = new SqlConnectionStringBuilder
                                                        {
                                                            DataSource = serverName,
                                                            InitialCatalog = databaseName,
                                                            IntegratedSecurity = true
                                                        };

            return GetSqlConnectionString(providerCs.ToString());
        }

        public static string GetSqlConnectionString(string providerConnectionString)
        {
            var namespaceString = typeof ($YourEdmxNameHere$Entities).Namespace;


            var fullName = typeof ($YourEdmxNameHere$Entities).Assembly.FullName;
            //This allows you to trim just the assembly name off the namespace while

            //leaving the  rest of the namespace

            string trimmedNamespace = namespaceString.Remove(0, fullName.IndexOf(",") + 1);

            var csBuilder = new EntityConnectionStringBuilder();
            csBuilder.Provider = "System.Data.SqlClient";
            csBuilder.ProviderConnectionString = providerConnectionString;
            csBuilder.Metadata = string.Format(
                "res://{0}/{1}.$YourEdmxNameHere$.csdl|res://{0}/{1}.$YourEdmxNameHere$.ssdl|res://{0}/{1}.$YourEdmxNameHere$.msl",
                fullName, trimmedNamespace);

            return csBuilder.ToString();
        }
    }

 

Enjoy!

Entity Framework, Productivity, Data Access

Composing Complex Queries with LINQ to Entities

30. April 2011

We have all had those times where we have had to build chains on complex where statements, with several OR / AND operations. These make LINQ queries look really complex and most of the time need to be reused in several places. To clean this up and give us the ability to compose complex queries on the fly from say a UI filter or something similar give the following a try.

public class Test
    {
        public void Testing()
        {
            Expression<Func<Product, bool>> isRed = c1 => c1.Color == "Red";

            Expression<Func<Product, bool>> isCheap = c2 => c2.StandardCost < 10.0m;

            Expression<Func<Product, bool>> isClothing = c3 => c3.Class == "Clothing";

            Expression<Func<Product, bool>> isAcceptable = Utility.BuildOrElse(isRed, isCheap, isClothing);

            IQueryable<Product> products = null;
            var query = products.Where(isAcceptable);
        }

    }

    public class ParameterRebinder : ExpressionVisitor
    {

        private readonly Dictionary<ParameterExpression, ParameterExpression> map;



        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {

            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();

        }



        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {

            return new ParameterRebinder(map).Visit(exp);

        }



        protected override Expression VisitParameter(ParameterExpression p)
        {

            ParameterExpression replacement;

            if (map.TryGetValue(p, out replacement))
            {

                p = replacement;

            }

            return base.VisitParameter(p);

        }

    }

    public static class Utility
    {

        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {

            // build parameter map (from parameters of second to parameters of first)

            var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);



            // replace parameters in the second lambda expression with parameters from the first

            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);



            // apply composition of lambda expression bodies to parameters from the first expression 

            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);

        }



        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {

            return first.Compose(second, Expression.And);

        }



        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {

            return first.Compose(second, Expression.Or);

        }

        public static Expression<Func<T, bool>> OrElse<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {

            return first.Compose(second, Expression.Or);

        }

        public static Expression<Func<T, bool>> BuildAnd<T>(params Expression<Func<T, bool>>[] conditions)
        {
            return conditions.Aggregate<Expression<Func<T, bool>>, Expression<Func<T, bool>>>(null, (current, expression) => current == null ? expression : current.And(expression));
        }

        public static Expression<Func<T, bool>> BuildOr<T>(params Expression<Func<T, bool>>[] conditions)
        {
            return conditions.Aggregate<Expression<Func<T, bool>>, Expression<Func<T, bool>>>(null, (current, expression) => current == null ? expression : current.Or(expression));
        }

        public static Expression<Func<T, bool>> BuildOrElse<T>(params Expression<Func<T, bool>>[] conditions)
        {
            return conditions.Aggregate<Expression<Func<T, bool>>, Expression<Func<T, bool>>>(null, (current, expression) => current == null ? expression : current.OrElse(expression));
        }

    }

Adapted and added to from

http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx

Entity Framework, Data Access, C#, C# Helpful Functions, Productivity

How to manage Queries with Entity Framework

26. April 2011

We have all looked at where statements all through out code and seen the same .Where() typed 20-30 times through out the code. It seems that when using LINQ we have such an easy time typing expressions and method chains with the fluent API that we have forgotten to obey DRY. ( Don’t Repeat Yourself ) Any line of code that has been written twice is a waste. If  writing the same code twice you are stealing, plain and simple! You are stealing away consistency and supportability, and are causing multiple points of change for future changes. Take the following code for example, and keep in mind this is a simple and the problem will be worse in larger code bases.

      static void Main(string[] args)
        {
            _repository = new EntityFrameworkRepository(new AdventureWorksEntities());
            _productRepository = new ProductRepository(_repository);

            _repository.AsQueryable<Product>().Where(x => x.Class == "Something");
            var longRunningProducts = _productRepository.GetLongRunningProducts();
        }

        public List<Product> GetProducts()
        {
            return _repository.AsQueryable<Product>().Where(p => p.Class == "Clothing").ToList();
        }

        public List<Product> GetInventory()
        {
            var items = _repository.AsQueryable<Product>().Where(p => p.Class == "Clothing").ToList();

            //Do Stuff

            return items;
        }

Now that we are able to look at the problem with open eyes the next question is how do we control this so that there is one place for this logic. The answer is query libraries.

static void Main(string[] args)
        {
            _repository = new EntityFrameworkRepository(new AdventureWorksEntities());
            _productRepository = new ProductRepository(_repository);

            _repository.AsQueryable<Product>().Where(x => x.Class == "Something");
            var longRunningProducts = _productRepository.GetLongRunningProducts();
        }

        public IEnumerable<Product> GetProducts()
        {
            return _repository.GetClothing();
        }

        public IEnumerable<Product> GetInventory()
        {
            var items = _repository.GetClothing();

            //Do Stuff

            return items;
        }

 

public static class ProductQueries
    {
        public static IQueryable<Product> GetClothing(this IRepository repository)
        {
            return repository.AsQueryable<Product>().Where(x => x.Class == "Clothing");
        }
    }

This allows for the control of queries and the usage of them across multiple areas without rewriting the .Where and it’s parameters everywhere. You can parameterize these further to increase reuse. Like so

 

public static class ProductQueries
    {
        public static IQueryable<Product> GetClothing(this IRepository repository)
        {
            return repository.GetByClass("Clothing");
        }

        public static IQueryable<Product> GetByClass(this IRepository repository, string className)
        {
            return repository.AsQueryable<Product>().Where(x => x.Class == className);
        }
    }

Entity Framework, Productivity

Entity Framework Cascading deletes avoid the gotchas

22. April 2011

If you have ever had to do Cascading deletes with Entity Framework you have realized that it is happiness, but it has a couple of gotchas. The Context that entity framework uses will not fetch all items related from the database just to issue delete statements, it will however issue deletes from anything it knows about. So the solution is to have the delete from the database cascade or bring the items into the context manually.

Setting it in the EDMX is easy. Just pull up the properties on the association and set the on Delete behavior.

image

There are a few more step to help avoid the gotchas.

First if you can specify the Delete rule on the Foreign Keys in the database.

image

If you cannot do that you can specify an include for the collections that you want to delete.

var employee = entities.Employees.Include("EmployeeAddresses").FirstOrDefault();
entities.DeleteObject(employee);

Or slightly cleaner to read but more trips to the database is to load the collections.

var employee = entities.Employees.FirstOrDefault();
employee.EmployeeAddresses.Load();
entities.DeleteObject(employee);

 

Hope this helps

Entity Framework, Productivity , ,

Entity Framework Connection Strings

13. April 2011

We have all felt the pain of the entity framework connection string being embedded with meta data. I ran into this today in an integration test and had to create full qualified pointers to the dll to get past the dreaded “Unable to load metadata resource” error. Here are the fruits of that labor.

public class EntityFrameworkConnectionStringBuilder
   {
       public static string GetEFConnectionString(string serverName, string databaseName)
       {
           var providerCs = new SqlConnectionStringBuilder
                                {
                                    DataSource = serverName,
                                    InitialCatalog = databaseName,
                                    IntegratedSecurity = true
                                };
           Type type = typeof(YourEntities);  
          
           var csBuilder = new EntityConnectionStringBuilder
                               {
                                   Provider = "System.Data.SqlClient",
                                   ProviderConnectionString = providerCs.ToString(),
                                   Metadata =
                                       string.Format(
                                           "res://{0}/{1}.YourEDMX.csdl|res://{0}/{1}.YourEDMX.ssdl|res://{0}/{1}.YourEDMX.msl",
                                           type.Assembly.FullName, TrimAssemblyNameOffNamespace(type))
                               };
           return csBuilder.ToString();
       }
       private static string TrimAssemblyNameOffNamespace(Type type)
       {
           //If you have a . in your dll name or your namespace is different
           //you will have to adjust this. In this example the namespace was
           // Project.Common and the Namespace was      //Project.Common.Repositories.ObjectContexts
           var result = type.Namespace.Substring(type.Namespace.IndexOf(".")+1);
           return result.Substring(result.IndexOf(".") + 1);
       }
   }

Enjoy!

Entity Framework, Productivity , ,

Legacy Support with Entity Framework–Stored Procs

8. April 2011

I have gotten several questions over the last few months over how to leverage Entity Framework with a large number of legacy stored procedures that cannot be re-written whole sale. The answer is slowly convert your data access to Entity framework using function imports, and as time permits move that logic into the query repository so that it can be unit tested and consistent.

Here is how to do it.

Make sure that you have added the stored procedures to the model.

image

Then right click the white background on the canvas…

image

This brings up the wizard…

image

1. Chose a Stored Procedure

2. Name the Method you will call in code for this.

3. Click the radio button for the complex type.

4. Click get column information.

5. Click Create New Complex Type – This saves a lot of manual creation.

6. Name your complex object.

7. Click Ok.

After these quick and easy steps you can then use this by calling the method on the entities.

image

Notice the Type safe parameters – This will help you avoid run time type mismatch issues throwing SQL Exceptions.

ObjectResult<BillOfMaterials> billOfMaterials = entities.GetBillOfMaterials()
billOfMaterials.Select(x => x.StandardCost);

You can then call against this just like any other collection of objects.

 

Enjoy

Entity Framework, Productivity , ,

Unit Testing Entity Framework Repository without a DB

30. March 2011

One of the problems that I have found is that I have trouble separating the data base calls from my unit tests while still covering my repository. We are going to talk about how to get around this, and pick up after this post to avoid some of the prep work.

We First add a Test Project to the solution to house the tests.

image

 

We want to setup a Product Repository so that we can test it but we want to mock the IRepository that it takes to avoid the database call.

var mockRepository = MockRepository.GenerateMock<IRepository>();
mockRepository.Stub(x => x.AsQueryable<Product>()).Return(new List<Product>
                                                                          {
                                                                              new Product()
                                                                                  {
                                                                                      DaysToManufacture = 4
                                                                                  },
                                                                              new Product()
                                                                                  {
                                                                                      DaysToManufacture = 2
                                                                                  }
                                                                          }.AsQueryable());
var target = new ProductRepository(mockRepository);

We setup the return with a value that should get filtered and a value that should not get filtered as to give us a control set. Make sure to call the AsQueryable on the object initialization so that it matches the return type on the repository.

After we have setup the test them we call our Long running products method.

 

//act
var result = target.GetLongRunningProducts();

//assert
Assert.IsTrue(result.Count() == 1);
Assert.AreEqual(4, result.FirstOrDefault().DaysToManufacture);

This test now gives us the ability to test our filters and our logical separation at the repository level without a database. We can leverage this to run integration performance and query tests against the database as well, but that is another post.

 

Source code is here

Data Access, Design Patterns, Entity Framework