Using Enums With LINQ To SQL
I don't know about you, but I'm quite a fan of using Enumerations (Enums) in my apps. I'm all for more readable, more explicit code because I think it helps a lot with maintainability, and enums help with that. I'd much rather read a line of code that says:
customer.CustomerType = CustomerType.Good;
than
customer.CustomerType = 1;
Of course, it means you also get Intellisense when you're writing the code. Another advantage is that enums, which are usually lookup types and very often bound to controls like comboboxes, will come down as part of the schema for your web service, negating calls to get the values.
So how can we make use of enums in LINQ To SQL? Actually, it's pretty easy.
Step 1: Create The Enum
This part should be familiar, as it's just a standard enum. I'm going to be working with Northwind and adding a CustomerType enum. Mine appears as follows:
public enum CustomerType
{
Good = 1,
Bad = 2,
Ugly = 3
}
Step 2: Add The New Column To Customers
The next step is to add the new column to your Customers table. In the database, just add it as a regular integer column:
Note: you can add an actual table into your database to hold these types as well, like a CustomerTypes table, but it's not strictly necessary. I would recommend doing so though and adding a foreign key reference to the Customers table, as it helps for things like reporting straight off your database.
Once you've done this, you'll need to add the property to your LINQ To SQL domain object. You can do this on the designer by dragging the new field onto an empty space on the designer. You'll get a duplicate copy of Customer ("Customer1" probably), then you can cut and paste the property onto the original entity. Obviously, you only need to do all this if you have an existing entity you're adding to.
The next step is critical. By default, the Type will come up as an "int (System.Int32)", but you can change it to the fully-qualified type of the enum (in my case, ConsoleApplication1.CustomerType). BUT, in order to locate it fully, you have to add the global identifier, as follows: global::ConsoleApplication1.CustomerType , so type that as is (but the equivalent for your namespace) into the textbox, as below:
That's it! You should now be able to use enums in your code directly, like we saw at the beginning. What's also cool is that you can now use them in your LINQ To SQL queries as well, like:
var customers = from c in dc.Customers
where c.CustomerType == CustomerType.Good
select c;
UPDATE: Here's a post on how you can generate the enum classes automatically from your database tables.