Social Icons

Pages

Handling Enum in Code First Entity Framework4.1

Hi All,
EF Code first approach has been developing(03-12-2012) and in version 4.1 it does not support mapping enum typed properties to database. You can find a few workarounds for that on the web. Each solution has its pros and cons, and I would like to present one, which is in my opinion easiest (in sense of coding effort) and most extensible.

1st lets create enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EntityFrameworkEnum
{
public enum LeaveStatus
{
Pending,
Approved,
Cancelled
}
}
view raw LeaveStatus.cs hosted with ❤ by GitHub

Then lets create LeaveStatusWrapper class as follows;

public class LeaveStatusWrapper
{
private LeaveStatus _leaveStatus;
public LeaveStatus leaveStatus
{
get { return _leaveStatus; }
set { _leaveStatus = value; }
}
public string StringValue
{
get { return _leaveStatus.ToString(); }
set { _leaveStatus = (LeaveStatus)Enum.Parse(typeof(LeaveStatus), StringValue, true); }
}
public static implicit operator LeaveStatusWrapper(LeaveStatus p)
{
return new LeaveStatusWrapper { leaveStatus = p };
}
public static implicit operator LeaveStatus(LeaveStatusWrapper pw)
{
if (pw == null) return LeaveStatus.Pending;
else return pw._leaveStatus;
}
}

Lets create Leave class;

public class Leave
{
[Key()]
public int Id { get; set; }
public LeaveStatusWrapper LeaveState { get; set; }
public string LeaveType { get; set; }
}
view raw Leave.cs hosted with ❤ by GitHub

then need to define data base context class as;

public class Context : DbContext
{
public DbSet<Leave> Leaves { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.ComplexType<LeaveStatusWrapper>();
}
}
view raw Context.cs hosted with ❤ by GitHub

We can write a test class for test this scenario as follows;

[TestClass]
public class TestEntityFrameworkEnum
{
private Context db = new Context();
[TestMethod]
public void TestEnum()
{
Leave leave = new Leave();
leave.Id = 1;
leave.LeaveType = "Casual";
leave.LeaveState = LeaveStatus.Pending;
db.Leaves.Add(leave);
db.SaveChanges();
Leave testLeave = getLeaveById(leave.Id);
Assert.AreEqual(leave.LeaveState, testLeave.LeaveState);
Leave leave2 = new Leave();
leave2.Id = 2;
leave2.LeaveType = "Medical";
leave2.LeaveState = LeaveStatus.Approved;
db.Leaves.Add(leave2);
db.SaveChanges();
Leave testleave2 = getLeaveById(leave2.Id);
Assert.AreEqual<LeaveStatus>(LeaveStatus.Approved, testleave2.LeaveState);
}
private Leave getLeaveById(int id)
{
Leave leave =null;
foreach (Leave item in this.db.Leaves)
{
if (item.Id == id)
{
leave = item;
break;
}
}
return leave;
}
}

Enjoy !!!


No comments:

Post a Comment