Question

I need some advice on best practices when creating an Entity and setting its (what are effectively enums) properties in .NET.

To take a simple example, let's say I have an object called 'Todo', which has three properties:
ID (int)
Text (string)
State (NotStarted, InProgress, Complete)

My Todo object will be stored in a SQL Server database, with the 'Type' property stored as an int. The State property will not have any other information or methods associated with it, it is just to mark the completeness of the Todo instance.

Should I be creating an enum (outside the Todo class) in Todo.cs as follows:

public enum TodoState  
{  
  NotStarted = 0,  
  InProgress = 1,  
  Complete = 2  
}

After which, I can create my Todo class as:

public class Todo
{
  public int Id { get; set; }
  public string Text { get; set; }
  public TodoState State { get; set; }
}

Or should I be creating a TodoState class that has an internal enum and static constructors? Or is there a better completely different way of doing this?

In addition to what you think would be the best way to achieve this in this instance, what are the industry standard way of approaching this kind of problem? Thanks in advance.

Was it helpful?

Solution

As of version 5 (with .NET 4.5), Entity Framework supports enum properties. Read Enum Support - Code First and Enumeration Support in Entity Framework for more information.

This is by far the easiest solution to your problem.

Your code looks good as is. I think you're on the right track, although here's a few minor suggestions:

  • Standard practice is to define one type per .cs file, including enums, so I recommend moving enum TodoState to TodoState.cs.
  • TodoState as a name works, but I think CompletionState is more descriptive of what it's supposed to represent.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top