Sunday, October 16, 2011

Detecting cycles in decimal digits and lists.

I was recently working on solving problem 64 for project Euler and one of the needed algorithms was a detection of cycles in a list. This routine works for detecting cycles in lists of cardinality greater than 2.

def get_cycle_len(N):
  i = k = 0
  for j in range(2, len(N)):
    if N[i] == N[j]:
      if k == 0:
        k = j
        i = 1
      else:
        if i == k:
          return k
        i += 1
    else:
      i = 0
      k = 0
  return -1

Saturday, October 8, 2011

Entity Framework June 2011 CTP Bug

I recently installed the Entity Framework June 2011 CTP to preview the enum support but ran into a bug along the way that reported an error while processing the template.


I encountered this error while trying to run an Entity based project using the "Database & Model First" paradigm. Uninstalling the preview removed the problem. Not sure why this error occured since the preview doesn't modify the assembly it is complaining about not finding an entry point in.

Wednesday, October 5, 2011

EF 4.1 Code First: Many one-to-one properties for same class type on an object.

I just started using the Entity Framework recently to employ persistence for an already established code base. Initially I was using the "Model & Database First" paradigm where a designer is used to layout the data model. Although, this ended up being tedious since my POCO instance had to exactly match the POCO proxy instance in my model designer view. After upgrading to EF 4.1, I realized the "Code First" paradigm was the way to go since I had to adapt the persistence model to my already existing code.

One of the earliest problems that I ran into was having more than one property on a class that referenced the same class type. This example was taken from a great site that explored the different EF properties.

public class Customer
{
 public int Id { get; set; }
 public int Age { get; set; }
 public Address BillingAddress { get; set; }
 public Address DeliveryAddress { get; set; }
}

Notice how both the BillingAddress and DeliveryAddress properties references the same class type. I kept trying to establish two 1-to-1 relationships on the class but this caused a problem with cascading deletes and foreign key constraints. I found a solution but it still required exceptional behavior on the part of my context and the database schema.

The most elegant solution was to just treat both of the properties as complex types. The only thing I had to do was remove the Id property from the properties' class and the context took care of the rest. So instead of two tables in the database (one for Customer and the other for Address), there would be only one. Below is a layout of what the table would look like.

Customer
{
 Id
 Age
 BillingAddress_City
 BillingAddress_Street
 BillingAddress_Zipcode
 DeliveryAddress_City
 DeliveryAddress_Street
 DeliveryAddress_Zipcode
}