问题
I want to create a helper method to check an item exists or not in datatabase.
I've tried this:
public static class DbContextExtensions
{
public static bool Exist<TModel>(this DbSet<TModel> model, string id) where TModel : class
{
return !string.IsNullOrEmpty(id) && model.SingleOrDefault(x => x.Id == id) != null;
}
}
I'm getting this error message:
'TModel' does not contain a definition for 'Id' and no extension method 'Id' accepting a first argument of type 'TModel' could be found (are you missing a using directive or an assembly reference?)
What I want to achieve:
public class PostManager
{
private readonly _dbContext;
public PostManager(MyDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<IdentityResult> UpdateAsync(EditPostViewModel model)
{
if (_dbContext.Users.Exist(model?.UserId) && _dbContext.Posts.Exist(model?.Id))
{
// the user with "UserId" and the post with "Id" are existing...
}
}
}
I don't want to create a helper method inside the PostManager class, like this:
public class PostManager
{
// contructor...
// actions...
private bool UserExist(string id)
{
return !string.IsNullOrEmpty(id) && _dbContext.Users.SingleOrDefault(x => x.Id == id) != null;
}
private bool PostExist(string id)
{
return !string.IsNullOrEmpty(id) && _dbContext.Posts.SingleOrDefault(x => x.Id == id) != null;
}
}
Because the method UserExist and PostExist may be used in many another classes. So, I don't want to re-declare them in every class before using.
How can I do that? Thank you so much!
回答1:
Your have TModel : class - since TModel is of type class which does not have any property named Id, hence the error. So you need to point it to a base entity class (preferably an interface - composition is always better than inheritance) but this is to give you a general idea - such as where TModel:Entity.
e.g.
class BaseEntity {
string Id {get; set;}
}
class Person : BaseEntity {
string Name {get; set;}
}
public static class DbContextExtensions
{
public static bool Exist<TModel>(this DbSet<TModel> model, string id) where TModel : BaseEntity
{
return !string.IsNullOrEmpty(id) && model.SingleOrDefault(x => x.Id == id) != null;
}
}
来源:https://stackoverflow.com/questions/48860276/how-to-write-an-extension-method-in-dbcontext-class