I created this function to generate a handle
(or slug
, as you prefer) for the model users, the problem is that I would like to make it more "modular", so I can easily implement in any other model you also need to generate a handle .
The model, which is a partial .
public partial class users
{
...
public void Handle()
{
...
}
}
The function:
public void Handle()
{
int length;
string handle;
List<int> list = new List<int>();
handle = Slugify.Make(this.first_name + " " + this.last_name);
length = (handle + "-").Length;
this.handle = handle;
using (Entities db = new Entities())
{
List<string> handles = db.users.Where(p => p.handle.Contains(handle) || p.handle.StartsWith(handle + "-"))
.Select(p => p.handle)
.ToList();
if (handles.Count == 0 || handles.Contains(handle) == false)
{
this.handle = handle;
return;
}
if (handles.Contains(handle) && handles.Count == 1)
{
this.handle = handle + "-" + 1;
return;
}
foreach (string index in handles)
{
if ((index + "-").Length > length)
list.Add(int.Parse(index.Remove(0, length)));
}
list.Sort();
int suffix = list.Last();
this.handle = handle + "-" + (suffix + 1);
}
}
So I created a separate class that would at first get the model parameter and then do basically what the Handle()
function does, but in a "modular" way, for example:
Passing as a parameter:
users user = new users
{
first_name = first_name,
last_name = last_name,
email = email,
password = BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt(6))
handle = Handle.Make(db.users, first_name + " " + last_name)
};
The function:
public class Handle
{
public string Make(Type model, string handle)
{
db.Set<model>.Where(...) ...
return handle;
}
}
But I can not pass the model db.users
as parameter without specifically determining that the type of this model
is users
.
I have tried public string Make(DbSet<dynamic> model...
but also did not give ...