我想创建一个辅助方法来检查数据库中是否存在一个项目。
我已经试过了:
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;
}
}
我收到此错误消息:
'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?)
我想要实现的目标:
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...
}
}
}
我不想在 PostManager
类中创建辅助方法,如下所示:
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;
}
}
因为 UserExist
和 PostExist
方法可能在许多其他类中使用。所以,我不想在使用前在每个类中重新声明它们。
我该怎么做?非常感谢!
最佳答案
您有 TModel : class
- 因为 TModel
属于类类型,它没有任何名为 Id
的属性,因此出现错误。所以你需要将它指向一个基础实体类(最好是一个接口(interface) - 组合总是比继承更好)但这是为了给你一个大概的想法 - 比如在哪里 TModel:Entity
。
例如
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;
}
}
关于c# - 如何在 DbContext 类中编写扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48860276/