DataAnnotations 和 FluentValidation 在 MVC 2 项目中不起作用

发布于 2024-09-25 20:19:59 字数 3086 浏览 5 评论 0原文

我已经编辑了原来的问题,因为发生了同样的错误,区别在于实现,我现在将 Ninject 添加到了混合中。

我已经为验证规则创建了一个类

public class AlbumValidator : AbstractValidator<Album> {
    public AlbumValidator() {
        RuleFor(a => a.Title).NotEmpty();
    }
}

我已经为 Ninject 创建了一个 ValidatorModule

internal class FluentValidatorModule : NinjectModule {
    public override void Load() {
        AssemblyScanner.FindValidatorsInAssemblyContaining<AlbumValidator>()
            .ForEach(result => Bind(result.InterfaceType).To(result.ValidatorType).InSingletonScope());
    }
}

这是我的 ValidatorFactory

public class NinjectValidatorFactory : ValidatorFactoryBase {
    public override IValidator CreateInstance(Type validatorType) {
        if (validatorType.GetGenericArguments()[0].Namespace.Contains("DynamicProxies")) {
            validatorType = Type.GetType(string.Format("{0}.{1}[[{2}]], {3}",
                validatorType.Namespace,
                validatorType.Name,
                validatorType.GetGenericArguments()[0].BaseType.AssemblyQualifiedName,
                validatorType.Assembly.FullName));
        }

        return Container.Get(validatorType) as IValidator;
    }

    IKernel Container { get; set; }
    public NinjectValidatorFactory(IKernel container) {
        Container = container;
    }
}

和我的 Global 中的相关部分

protected override void OnApplicationStarted() {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

        var factory = new NinjectValidatorFactory(Container);

        ModelValidatorProviders.Providers.Add(
            new FluentValidationModelValidatorProvider(factory));

        DataAnnotationsModelValidatorProvider
            .AddImplicitRequiredAttributeForValueTypes = false;
    }

    protected override IKernel CreateKernel() {
        return Container;
    }

    IKernel Container {
        get { return new StandardKernel(new FluentValidatorModule()); }
    }

我加载示例站点,单击创建新相册链接,然后单击创建按钮,将标题留空 I然后我遇到了错误 protected override void OnApplicationStarted() { AreaRegistration.RegisterAllAreas(); 注册路由(RouteTable.Routes);

        var factory = new NinjectValidatorFactory(Container);

        ModelValidatorProviders.Providers.Add(
            new FluentValidationModelValidatorProvider(factory));

        DataAnnotationsModelValidatorProvider
            .AddImplicitRequiredAttributeForValueTypes = false;
    }

    protected override IKernel CreateKernel() {
        return Container;
    }

    IKernel Container {
        get { return new StandardKernel(
            new Bootstrapper(),
            new FluentValidatorModule()); }
    }

我加载创建表单并单击创建,将标题留空,然后看到一个错误

This property cannot be set to a null value.

它引用的行位于实体框架自动生成的类中,我跟踪它

Namespace.Contains("DynamicProxies")

并且它返回 false,这是因为我告诉 EF 使用自定义命名空间 SampleMusicStore.Web?

或者我还缺少其他东西吗?

干杯。

I have edited the original question since the same error is occurring the difference being the implementation, I have now added Ninject to the mix.

I have created a class for the validation rules

public class AlbumValidator : AbstractValidator<Album> {
    public AlbumValidator() {
        RuleFor(a => a.Title).NotEmpty();
    }
}

I have created a ValidatorModule for Ninject

internal class FluentValidatorModule : NinjectModule {
    public override void Load() {
        AssemblyScanner.FindValidatorsInAssemblyContaining<AlbumValidator>()
            .ForEach(result => Bind(result.InterfaceType).To(result.ValidatorType).InSingletonScope());
    }
}

Here is my ValidatorFactory

public class NinjectValidatorFactory : ValidatorFactoryBase {
    public override IValidator CreateInstance(Type validatorType) {
        if (validatorType.GetGenericArguments()[0].Namespace.Contains("DynamicProxies")) {
            validatorType = Type.GetType(string.Format("{0}.{1}[[{2}]], {3}",
                validatorType.Namespace,
                validatorType.Name,
                validatorType.GetGenericArguments()[0].BaseType.AssemblyQualifiedName,
                validatorType.Assembly.FullName));
        }

        return Container.Get(validatorType) as IValidator;
    }

    IKernel Container { get; set; }
    public NinjectValidatorFactory(IKernel container) {
        Container = container;
    }
}

and the relevant parts from my Global

protected override void OnApplicationStarted() {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

        var factory = new NinjectValidatorFactory(Container);

        ModelValidatorProviders.Providers.Add(
            new FluentValidationModelValidatorProvider(factory));

        DataAnnotationsModelValidatorProvider
            .AddImplicitRequiredAttributeForValueTypes = false;
    }

    protected override IKernel CreateKernel() {
        return Container;
    }

    IKernel Container {
        get { return new StandardKernel(new FluentValidatorModule()); }
    }

I load the sample site click on the create new album link and then click the create button leaving the title empty I am then greeted with the error protected override void OnApplicationStarted() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);

        var factory = new NinjectValidatorFactory(Container);

        ModelValidatorProviders.Providers.Add(
            new FluentValidationModelValidatorProvider(factory));

        DataAnnotationsModelValidatorProvider
            .AddImplicitRequiredAttributeForValueTypes = false;
    }

    protected override IKernel CreateKernel() {
        return Container;
    }

    IKernel Container {
        get { return new StandardKernel(
            new Bootstrapper(),
            new FluentValidatorModule()); }
    }

I load up the create form and click create leaving the title empty low and behold an error

This property cannot be set to a null value.

The line it references is within the Entity Framework auto generated class, I traced the

Namespace.Contains("DynamicProxies")

and it was returning false, is this because I told EF to use a custom namespace SampleMusicStore.Web?

Or am I missing something else?

Cheers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隔岸观火 2024-10-02 20:19:59

问题是实体框架在您的类上生成动态代理,然后您的系统尝试根据代理类而不是您定义的类进行验证。

解决此问题的方法与此相同 答案

The problem is that Entity Framework is generating dynamic proxies on your classes, and then your system is trying to validate against the proxy classes instead of the classes you defined.

The way to resolve this is the same as this answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文