2024年5月17日 星期五

自訂權限驗證機制

// 使用 filter
[Route("api/[controller]")]
[ApiController]
[Authorize]
[TypeFilter(typeof(CustomAsyncAuthorizationFilter))]
public class Controller1 : ControllerBase

// 定義 filter
public sealed class CustomAsyncAuthorizationFilter : IAsyncAuthorizationFilter
{
    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        bool isAuthorized = await CheckUserAuthorizationAsync(context);
        if (!isAuthorized) context.Result = new ForbidResult();
    }
    private async Task<bool> CheckUserAuthorizationAsync(AuthorizationFilterContext context)
    {
       // do something and return bool
    }

2024年1月31日 星期三

Entity Framework 建立新物件並儲存後馬上取得關聯資料

使用 CreateProxy 建立物件,不要直接 new
var newmodel = _contextXXX.CreateProxy<yyy>();
...
_contextXXX.yyy.Add(newmodel);
await _contextXXX.SaveChangesAsync();
var aaa=newmodel.xxx.yyy; 

或者直接reload 物件
await _contextXXX.Entry<yyy>(newmodel).ReloadAsync();

2023年7月11日 星期二

EF 圖表加入新table 無效

此為 visual studio 某一版之後產生的bug,暫時性解法如下

Start Notepad in administrator mode, and open the file (substituting Community for Professional or Enterprise depending on your version):

C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\Templates\Includes\EF6.Utility.CS.ttinclude

Update the following code in DynamicTextTransformation (approx line 1920) and change:

_generationEnvironment = type.GetProperty(“GenerationEnvironment”, BindingFlags.Instance | BindingFlags.NonPublic);

to

_generationEnvironment = type.GetProperty(“GenerationEnvironment”, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

2023年4月6日 星期四

entity framework 刪除 table record 相依 table 殘留現象

entity framework 刪除 table record 無法針對相依 table 套用 資料庫刪除規則:重疊顯示
若相依table 的欄位不允許null 則會刪除失敗,若允許null 則會改為 null
必須手動刪除相依資料!!

※ EF6 db first 會有這問題,不確定 core 和 code first 是否有相同情形

2023年3月10日 星期五

2023年3月9日 星期四

一段時間未操作系統,下一次動作會卡頓

資料庫連接字串設定 Min Pool Size 避免連接池中的未使用連接在一段時間(大約 4-8 分鐘)後被釋放,因為沒有可用連接而重新產生連接會等待數秒鐘

參考資料

調整 IIS 應用程式集區進階設定,把閒置逾時動作改成Suspend ,避免集區重啟造成連接池消失

參考資料

自訂權限驗證機制

// 使用 filter [Route("api/[controller]")] [ApiController] [Authorize] [TypeFilter(typeof(CustomAsyncAuthorizationFilter))] public c...