c# - 如何在 DbContext 类中编写扩展方法?

标签 c# entity-framework

我想创建一个辅助方法来检查数据库中是否存在一个项目。

我已经试过了:

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;
    }
}

因为 UserExistPostExist 方法可能在许多其他类中使用。所以,我不想在使用前在每个类中重新声明它们。

我该怎么做?非常感谢!

最佳答案

您有 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/

相关文章:

javascript - 如何使用 Javascript 从 asp.net 的下拉列表中获取选定的值?

c# - ef代码第一个principal和dependent的区别

c# - 英孚流利 API : Set property for each entity derived from a base abstract class

wpf - Entity Framework 在克隆后附加异常

c# - 在 Linq 中使用 OrderBy

c# - 将字符串转换为 System.Data.SqlTypes.SqlBytes C#

c# - 我的程序无故从一行跳到另一行 (C#)

c# - MonoMac 事件 - 更改 NSTable 行的颜色

c# - 将数据集传递给存储过程

c# - 实体 IEnumerable 仅获取基类 - 而不是派生类