简体   繁体   中英

How to pass DbSet as generic parameter?

I have a custom validator for FluentValidation to validate whether Guid exist in the Database.

public static class TestCustomValidator
{
    public static IRuleBuilderOptions<T, Guid> MustExistInDatabase<T>(this IRuleBuilder<T, Guid> ruleBuilder, ApplicationContext context)

    return ruleBuilder.Must(id => context.Product.Find(id) != null).WithMessage("'{PropertyName}' {PropertyValue} not found.");
}

Then I will call it like this

RuleFor(r => r.ProductId).NotEmpty().MustExistInDatabase(context);

However, this part context.Product.Find(id) != null is currently only for Product and I have a lot of tables so I was hoping I could do something like

RuleFor(r => r.ProductId).NotEmpty().MustExistInDatabase<Product>();  
RuleFor(r => r.CustomerId).NotEmpty().MustExistInDatabase<Customer>();  

And it would automatically look for the Product or Customer table. Any idea how to do this?

You can define a base class as follows and inherit entities from it

public abstract class BaseEntity
{
    public Guid Id { get; set; }
}

public class Product : BaseEntity
{
    //other properties
}

public class Customer : BaseEntity
{
    //other properties
}

Then change your extension method as below

public static IRuleBuilderOptions<T, Guid> MustExistInDatabase<T>(this IRuleBuilder<T, Guid> ruleBuilder, ApplicationContext context) where T : BaseEntity
{
   return ruleBuilder.Must(id => context.Set<T>().Find(id) != null).WithMessage("'{PropertyName}' {PropertyValue} not found.");
}

and use as follows:

RuleFor(r => r.ProductId).NotEmpty().MustExistInDatabase<Product>(dbContext);  
RuleFor(r => r.CustomerId).NotEmpty().MustExistInDatabase<Customer>(dbContext);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM