簡體   English   中英

如何將 DbSet 作為泛型參數傳遞?

[英]How to pass DbSet as generic parameter?

我有一個 FluentValidation 的自定義驗證器來驗證數據庫中是否存在Guid

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.");
}

然后我會這樣稱呼它

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

但是,這部分context.Product.Find(id) != null目前僅適用於Product並且我有很多表,所以我希望我可以做類似的事情

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

它會自動查找ProductCustomer表。 知道怎么做嗎?

您可以如下定義基礎 class 並從中繼承實體

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

public class Product : BaseEntity
{
    //other properties
}

public class Customer : BaseEntity
{
    //other properties
}

然后更改您的擴展方法如下

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.");
}

並使用如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM