Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用FluentValidation库验证实体_C#_Validation_Fluentvalidation - Fatal编程技术网

C# 使用FluentValidation库验证实体

C# 使用FluentValidation库验证实体,c#,validation,fluentvalidation,C#,Validation,Fluentvalidation,在执行更新或删除之前,如何检查实体本身是否存在 我尝试使用类似下面的代码,但得到一个错误“必须指定属性名”。如何实现这样的逻辑 public CustomValidator() { RuleFor(x=>x).Must(ExistsInDatabase).WithMessage("Attempt to work with nonexistent entity"); } private bool ExistsInDatabase(MyClass myClassInstance)

在执行更新或删除之前,如何检查实体本身是否存在

我尝试使用类似下面的代码,但得到一个错误“必须指定属性名”。如何实现这样的逻辑

public CustomValidator()
{
     RuleFor(x=>x).Must(ExistsInDatabase).WithMessage("Attempt to work with nonexistent entity");
}

private bool ExistsInDatabase(MyClass myClassInstance)
{

     if (myClassInstance == null)
           return false;

     return true;

   }

更新:问题涉及RuleFor()中的语法-是否可以在不指定特定属性的情况下使用(x=>x)?或者以其他方式检查正在验证的整个实体的状态?

我认为您需要在ExistsInDatabase类中写入更多功能,以便它能够在数据库中执行查找,以查看是否存在具有相同主键的实体

如果您使用的是实体框架,那么可以在ExistsInDatabase类上使用泛型,这样它就可以调用您的上下文。您可以向上下文类添加一个简单的帮助器

public virtual IDbSet<T> DbSet<T>() where T : class
    {
        return this.Set<T>();
    }
公共虚拟IDbSet DbSet(),其中T:class
{
返回这个.Set();
}
一旦有了一个集合,就可以使用effind方法,该方法将基于主键进行搜索。比如像这样的东西

var result = context.DbSet<Business>().Find(1);
return result == null ? false : true;
var result=context.DbSet().Find(1);
返回结果==null?假:真;

如何将整个实体传递给ExistsInDatabase()方法?当您说RuleFor(x=>x)时,必须(ExistsInDatabase)此时x的值是多少?你们能展示一下你们是如何使用它的吗?也许是测试方法中的广告,展示了它的使用情况。从那里,我们将能够确定您可以如何继续。我要做的事情是,我所有的实体都继承自一个基类,这是一个具有特定属性的抽象类。如果您有,您可以简单地期望它作为ExistsInDatabase方法中的一个参数。