![](/img/trans.png)
[英]how to access db context within a static method/class in asp.net core 2
[英]How can pass a data context to a static method in Asp .Net Core
我想將 ApplicationContext 傳遞給 static 方法。 我嘗試了很多不同的方法,但沒有任何效果。 我在沒有靜態的情況下嘗試過,而且上下文總是返回 null。
這是我編寫的原始代碼,但它給出了錯誤“非靜態字段、方法或屬性需要 object 引用”
public class SelectItemHelper
{
private readonly ApplicationContext db;
public SelectItemHelper(ApplicationContext context)
{
db = context;
}
public static IEnumerable<SelectListItem> GetDeveloper()
{
var developer = db.Games.ToList();
IList<SelectListItem> items = new List<SelectListItem>();
foreach (var dev in developer)
{
items.Add(new SelectListItem {Text = dev.Article, Value = dev.Article });
}
return items;
}
}
static
關鍵字,從而使該方法成為實例成員services.AddScoped<SelectItemHelper>();
. 因此,您可以簡單地注入您的 class:在 controller 或視圖中(使用@inject
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.