![](/img/trans.png)
[英]How to pass an string as a type parameter for a generic DbSet in Entity Framework?
[英]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>();
它會自動查找Product
或Customer
表。 知道怎么做嗎?
您可以如下定義基礎 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.