星期三, 3月 19, 2025

[EFCore] 陰影屬性

通常 EF Entity Property 會對應 Table Column,但透過陰影屬性 (Shadow Property) 可以讓該 EF Entity 沒有該 Property,但卻還是可以對應 Table Column。 適用場景在於 Table 常設的 CreateTime、ModifiedDate 欄位或是資料軟刪除欄位

Shadow Property 設定

在 DbContext 內的 OnModelCreating 中透過 Fluent API 來進行設定
public partial class AdventureWorks2022DbContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
            .Property<DateTime>("ModifiedDate");
    }
}

C# Code

namespace EFCoreShadowProperty
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string shadowPropertyName = "ModifiedDate";

            var dbContext = new AdventureWorks2022DbContext();

            Console.WriteLine("---------- 在 OrderBy 中使用 EF.Property 來抓取 Shadow Property");
            var person = dbContext
                .Person
                .OrderBy(p => EF.Property<DateTime>(p, shadowPropertyName))
                .FirstOrDefault();

            // 取值並顯示
            var modifyDate = dbContext.Entry(person).Property(shadowPropertyName).CurrentValue;
            Console.WriteLine($"---------- 修改時間最早的資料:{person.LastName}-{person.FirstName}-{modifyDate}");

            Console.WriteLine($"---------- 設定 Shadow Property 值並儲存");
            // 設定值並儲存
            DateTime now = DateTime.Now;
            dbContext.Entry(person).Property(shadowPropertyName).CurrentValue = now;
            dbContext.SaveChanges();

            Console.WriteLine($"---------- 在 Where 中使用 EF.Property 來抓取 Shadow Property");
            var updatePerson = dbContext
                .Person
                .Where(p => EF.Property<DateTime>(p, shadowPropertyName) == now)
                .ToList();
        }
    }
}

輸出結果觀察


設定 [EFCore] LogTo 來觀察 Shadow Property 所產生的 TSQL,以下有把輸出資訊簡化,方便閱讀
---------- 在 OrderBy 中使用 EF.Property 來抓取 Shadow Property

SELECT TOP(1) 欄位名稱
FROM [Person].[Person] AS [p]
ORDER BY [p].[ModifiedDate]

---------- 修改時間最早的資料:Tamburello-Roberto-2007/11/4 上午 12:00:00

---------- 設定 Shadow Property 值並儲存

SET IMPLICIT_TRANSACTIONS OFF;
SET NOCOUNT ON;
UPDATE [Person].[Person] SET [ModifiedDate] = @p0
WHERE [BusinessEntityID] = @p1;
SELECT @@ROWCOUNT;

---------- 在 Where 中使用 EF.Property 來抓取 Shadow Property

SELECT 欄位名稱
FROM [Person].[Person] AS [p]
WHERE [p].[ModifiedDate] = @__now_0

沒有留言:

張貼留言