[英]c# need to have one extension method for various classes
What i am trying to do is i need to have one extension method for all my models.我想要做的是我需要为我的所有模型提供一种扩展方法。
Let's assume i have 3 class/models.假设我有 3 个类/模型。
i am trying to do something like this in my extension method (was not able to succeed).我正在尝试在我的扩展方法中做这样的事情(未能成功)。
public static IQueryable<T> IncludeAllInfo<T>(this IQueryable<T> model)
{
if(model.getType().ToString() == "Model1")
{
var newModel = model.asQueryable<Model1>();
return newModel.Include(a => a.Model2).Include(a => a.Model3);
}
elseif(model.getType().ToString() == "Model2")
{
var newModel = model.asQueryable<Model2>();
return newModel.Include(a => a.Model3);
}
}
is this possible or must i create overload method for each type?这是可能的还是必须为每种类型创建重载方法?
Create one extension for every entity为每个实体创建一个扩展
public static IQueryable<MyEntity> IncludeAllInfo(this Dbset<MyEntity> model)
{
return model.Include(a => a.Model3);
}
Or或者
public static IQueryable<MyEntity> IncludeAllInfo(this IQueryable<MyEntity> model)
{
return model.Include(a => a.Model3);
}
You should create 1 method per type.您应该为每种类型创建 1 个方法。
public static IQueryable<Model1> IncludeAllInfo(this IQueryable<Model1> model) {
return model.Include(a => a.Model2).Include(a => a.Model3);
}
public static IQueryable<Model2> IncludeAllInfo(this IQueryable<Model2> model) {
return model.Include(a => a.Model3);
}
This is easier to test, maintain, read, and it is less code than what you have above.这更容易测试、维护、阅读,而且代码比上面的代码少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.