Hello,
Using c# and ASP .Net Core 6 I have an N-Tier web application that has implemented a Repository Pattern and Unit of Work.
In this web application, an Admin can create a Hashtag, based on the following model:
public class Hashtag
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50, ErrorMessage = "Name cannot be longer than 50 characters.")]
public string Name { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Description cannot be longer than 100 characters.")]
public string Description { get; set; }
}
In the IHashtagRepository.cs I have added the following Method:
public interface IHashtagRepository : IRepository<Hashtag>
{
bool CheckIfHashtagExists(string name);
}
In the HashtagRepository.cs I have the following:
public bool CheckIfHashtagExists(string name)
{
var objFromDb = _db.Find(e => e.Name == name);
return objFromDb.Any();
}
In the OnPost() Method of the Create.cshtml.cs I would like to ensure that the Hashtag.Name is distinct (not a duplicate).
I though of doing something like this:
var objExists = CheckIfHashtagExists(somenamehere);
if (objExists = True)
{
Do some stuff
}
else
{
Do something else
}
I am getting an error on this line in HashtagRepository.cs
var objFromDb = _db.Find(e => e.Name == name);
Compiler Error CS1061
type' does not contain a definition for 'name' and no accessible extension method 'name' accepting a first argument of type 'type' could be found (are you missing a using directive or an assembly reference?).
I am unsure how to correct this error.
Also, I am unsure if there is a more correct way to achieve what I am attempting to do.
My Generic Repository has the following Mathods available in the Interface:
public interface IRepository<T> where T : class
{
T Get(int id);
IEnumerable<T> GetAll();
IEnumerable<T> Find(Expression<Func<T, bool>> expression);
T GetFirstOrDefault(Expression<Func<T, bool>>? filter = null, string? includeProperties = null);
void Add(T entity);
void Remove(int id);
void Remove(T entity);
void RemoveRange(IEnumerable<T> entity);
}
Thanks in advance for your help.
It is much appreciated.