9
how would you design this scenario (using Entity Framework 4.1, Code First and repository pattern): the Visual Studio solution contains the following projects
Solution
|-Web Application Project
|-DAL Project
|-Model Project
So in the Model Project there are various classes. Suppose we have in there a class called User with the following definition (stripped down):
public class User{
[Key]
public int UserId { get; set; }
....
//this property has a unique constraint created in a custom DB Initializer class
public string email { get; set; }
....
}
In the DAL Project reside the repository methods (Insert, Update etc.) and also the Initializer class:
public class MyDatabaseInitializer : IDatabaseInitializer<MyDatabase>
{
public void InitializeDatabase(MyDatabase context)
{
try
{
if (!context.Database.Exists())
{
context.Database.Create();
context.Database.ExecuteSqlCommand(
"ALTER TABLE Users ADD CONSTRAINT uc_Email UNIQUE(Email)");
}
}
catch (Exception ex)
{
throw ex.InnerException;
}
}
}
The Commit method of my Unit of Work class looks like this:
public string Commit()
{
string errorMessage = string.Empty;
try
{
Database.Commit();
}
catch (DbUpdateException updExc)
{
errorMessage = updExc.InnerException.Message;
}
return errorMessage;
}
As you see I'm handling DbUpdateException in the Commit() method of the Unit of Work class; this means for each class which could cause an update error, this would be handled here.
Suppose one inserts the User records with the following Data:
(U