我正在嘗試構建一個在Azure中託管的webservice API應用程序,該應用程序在數據庫中查找產品價格。這是使用C#中的Visual Studio 2017開發的。對C#,MVC和.netcore相對陌生(我知道,不是一個好的起點:-))我一直在關注各種教程,並遵循設計最佳實踐來開發webapp。這包括使用Repository Pattern方法創建一個接口作爲控制器的一部分。MVC存儲庫模式查詢緩存問題
namespace i*******api.Models
{
public interface IPrice
{
LiveProduct Find(string sku, string cCode);
}
}
然後
namespace i*******api.Models
{
public class Price : IPrice
{
static List<LiveProduct> LiveList = new List<LiveProduct>();
private readonly ApplicationDbContext _context;
public Price(ApplicationDbContext context)
{
_context = context;
}
public LiveProduct Find(string findSKU, string cCode)
{
var prices = (from m in _context.LiveProduct
where m.countryCode == cCode && m.sku == findSKU
select m).FirstOrDefault();
return prices;
}
終於控制器...
namespace i*******api.Controllers
{
[Produces("application/json")]
[Route("api/Prices")]
public class PricesController : Controller
{
public IPrice PriceRepo { get; set; }
public PricesController(IPrice _repo)
{
PriceRepo = _repo;
}
[HttpGet("{id}", Name = "GetPrice")]
public IActionResult GetById(string id, string cCode)
{
var item = PriceRepo.Find(id,cCode);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
}
}
的代碼,上面的,原則上工作正常,我可以鍛鍊這一點,並取回正確的結果我第一次打電話給這個。有一個單獨的web應用程序更新這個數據庫,如果價格單獨更新,上面的API查詢繼續返回原始數據,而不是更新結果。
查看並搜索了這個問題,我假設有一般的EF類型緩存正在進行,並且我應該使用類似AsNoTracking()
或類似的東西來防止此緩存發生?不過,我無法看到在上述場景中應用AsNoTracking()
(例如,它不會讓我添加using
名稱空間) - 但這是我認爲我的經驗不足真的踢在:-(
當我調試,我可以在第一時間看到這個運行時創建的_context
但這不是重複任何後續查詢。PriceRepo = _repo
每次但not _context = context
發生。
我希望得到一些幫助,以解決這一點,並希望這是一些簡單的我只是想念
一般來說,如果您要遵循此模式並使用實體框架,則應將EF上下文視爲工作單元,這意味着您應該將上下文封裝到每個存儲庫方法中的使用塊中。 –
您是如何配置DI容器以將價格注入控制器的? –
聽起來像你正在註冊你的DbContext作爲單身人士,你不應該這樣做。 DbContext應該始終註冊爲有作用域(每個請求一個實例) – Tseng