Post Categories

There are several attributes available when using code first with the Entity Framework 4 CTP5 Code First option. When working with strings you can use [MaxLength(length)] to control the length and [Required] will work on all properties. But there are a few things missing. By default all string will be created using unicode so you will get nvarchar instead of varchar. You can change this using the fluent API or you can create an attribute to make the change. If you have a lot of properties, the attribute will be much easier and require less code.

You will need to add two classes to your project to create the attribute itself:

Once you have this done, you can use the attribute in your classes to make sure that you get database types of varchar instead of nvarchar:

1: [Unicode(false)]

2:publicstring Name { get; set; }

Another option that is missing is the ability to set the precision and scale on a decimal. By default decimals get created as (18,0). If you need decimals to be something like (9,2) then you can once again use the fluent API or create a custom attribute. As with the unicode attribute, you will need to add two classes to your project:

Both these options use the same concepts so if there are other attributes that you want to use, you can create them quite simply. The key to it all is the PropertyConfiguration classes. If there is a class for the datatype, then you should be able to write an attribute to set almost everything you need. You could also create a single attribute to encapsulate all of the possible string combinations instead of having multiple attributes on each property.

All in all, I am loving code first and having attributes to control database generation instead of using the fluent API is huge and saves me a great deal of time.