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

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 , ,

Strategies for becoming a better programmer

7. December 2010

I just saw this come across my blog roll and figured it was worth the recommend. He makes some very good points about reading to much and trying to little. Definitely worth the read.

 

http://blog.developwithpassion.com/2010/12/strategies-for-becoming-a-better-programmer

 

Enjoy

Productivity

Time and Resources

1. November 2010

I have been spending my time and resources now working on getting to know Ruby and Java and trying to fully grasp OO principles. I want to make sure that no matter the language that I am using that I am writing the best code I can and that it adheres to the principles or Object oriented programming and design. To that end I started following a lot of new blogs, and this caused me to find more than one that has hit on the subject that I agree with more and more.

 

Developers should not specialize. Just like using FizzBuzz and other standard interview coding questions to understand the logical steps a person takes to write code. We should be pushing for a concept driven programmer instead of an implementation specialist. If you have a conceptually strong programmer you can throw almost any technology at them and they will succeed. If you have someone who doesn’t understand the concepts and has focused on the specific implementation they know it will take much longer.

 

Enjoy the post below. I did.

http://davybrion.com/blog/2010/10/developers-shouldnt-specialize/

Productivity

Absolute Must Read!!!

30. October 2010

If http://elegantCode.com is not on your blog roll, please take a look. This is a must read for pro devs.

http://elegantcode.com/2010/10/27/laborers-versus-professionals/

 

Enjoy. Thank you to Jan Van Ryswyck for the article.

Productivity