I am trying to implement the Repository Pattern with a Unit of work but I don't know if I am on the right direction. This is my Model:
public class Resource
{
public string RessourceUID { get; set; }
public string RessourceName { get; set; }
public List<Team> Teams { get; set; }
public string Loginname { get; set; }
}
This is my Repository:
public class ResourceRepository
{
public static Resource GetResourceByLoginname(string loginname)
{
return RunWithElevatedPrivileges(() => GetResourceByLoginnameInternal(loginname));
}
private static Resource GetResourceByLoginnameInternal(string loginname)
{
return ExecuteSql(cmd =>
{
Resource resource;
cmd.CommandText = @"SELECT convert(nvarchar(36), ResourceUID) AS ResourceUID, UserClaimsAccount, ResourceName FROM MSP_EpmResource_UserView WHERE UserClaimsAccount = @userclaimsaccount";
cmd.Parameters.AddWithValue("@userclaimsaccount", SqlDbType.NVarChar).Value = loginname;
using (var dr = cmd.ExecuteReader())
{
if (!dr.HasRows)
return null;
resource = new Resource();
while (dr.Read())
{
MapResourceData(resource, dr);
resource.Teams = RunWithElevatedPrivileges(() => GetResourceTeams(resource));
}
}
return resource;
});
}
private static void MapResourceData(Resource resource, SqlDataReader dr)
{
resource.RessourceUID = SqlReaderHelper.GetValue<string>(dr, "ResourceUID");
resource.RessourceName = SqlReaderHelper.GetValue<string>(dr, "ResourceName");
resource.Loginname = SqlReaderHelper.GetValue<string>(dr, "UserClaimsAccount");
}
private static T RunWithElevatedPrivileges<T>(Func<T> action)
{
var result = default(T);
Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(() => result = action());
return result;
}
private static void ExecuteSql(Action<SqlCommand> action)
{
string connectionString = Connectivity.GetConnectionString();
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
var cmd = conn.CreateCommand();
action(cmd);
cmd.ExecuteNonQuery();
}
}
private static T ExecuteSql<T>(Func<SqlCommand, T> action)
{
T result;
string connectionString = Connectivity.GetConnectionString();
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
var cmd = conn.CreateCommand();
result = action(cmd);
cmd.ExecuteNonQuery();
}
return result;
}
}
- Is this a good design?
- Is this the Repository Pattern?
- What could I optimize?
- I absolutely don't know how to implement the Unit of work. How could I do this?
- Should I move the
ExecuteSqlmethods out of the Repository? - Should I also move the
MapXXXDatamethods out of this Repository?