Search code examples
c#entity-framework-4.1business-logic

Business Logic that depends on string values


In one of my projects I am working on I am using Entity Framework 4.1 (Code First). I have a relationship between two entities like the following:

public class Project
{
    public int Id { get; set; }

    // snip...

    // Foreign Key
    public string ProjectId { get; set; }

    // navigation proeprty
    public virtual ProjectType ProjectType { get; set; }
}

public class ProjectType
{
    public string Id { get; set; }

    public virtual ICollection<Project> Projects { get; set; }
}

Right now I business logic that depends on what type of project is being created/edited so I have code like this:

if( "P".Equals(project.ProjectTypeId) )
    // logic goes here

Is there some other way to do this that doesn't rely on me comparing string values?


Solution

  • I'd personally prefer converting ProjectTypeId to an enum type.

    var projectType = Enum.Parse(typeof(ProjectType), project.ProjectTypeId);
    switch(projectType)
    {
        case ProjectType.P: // logic goes here
        case ProjectType.N:
            break;
        default: throw new ArgumentOutOfRangeException("That wasn't a valid project type");
    }
    

    I'm assuming that you have a fixed number of ProjectTypes, and that your code is supposed to be aware of all of them. This approach gives you a single "source of truth" to look at when you need to see all the ProjectTypes that can be used. I prefer this over other options like a class with string constants because:

    1. It's easier to "fail fast" if you discover that the project has an invalid project type.
    2. You can pass ProjectTypes around as strongly-typed parameters to utility functions and such.