簡體   English   中英

Entity Framework Core 使用 UDF 定義屬性

[英]Entity Framework Core define property using a UDF

EF 新手,有以下場景。 我創建了幾個非常基本的表/類來演示我想要實現的目標(請原諒下面可能存在的任何潛在拼寫問題,我只是將其作為示例輸入)。

   //Model Class
    public class Customer{
        public long Id{ get; private set; }
        public string name{ get; private set; }
        public long status{ get; private set; }
    }

//configuration
public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
    public void Configure(EntityTypeBuilder<Customer> builder)
    {
        builder.ToTable("Customer");

        builder.HasKey(e => e.Id);

        builder.Property(e => e.Id)
            .HasColumnName("Id")
            .ValueGeneratedNever()
            .IsRequired();

        builder.Property(e => e.name)
            .HasColumnName("name")
            .IsRequired();

    }
}

//Tables
CREATE TABLE [dbo].[Customer](
    [Id] [uniqueidentifier] NOT NULL,
    [name] [nvarchar](255) NOT NULL )


CREATE TABLE [dbo].[CustomerJournal](
    [Id] [bigint] NOT NULL,
    [RowId] [int] IDENTITY(1,1) NOT NULL,
    [CustomerId] [bigint] NOT NULL,
    [StatusId] [bigint] NOT NULL,
    [StatusAlias] [varchar](32) NOT NULL,
    [StatusName] [nvarchar](128) NOT NULL,
    [CreateDate] [datetimeoffset](7) NOT NULL
)


ALTER TABLE [dbo].[CustomerJournal]  WITH CHECK ADD  CONSTRAINT [FK_CustomerJournal_Customer] FOREIGN KEY(CustomerId)
REFERENCES [dbo].[Customer] ([Id])
GO

CustomerJournal 是客戶狀態的日志。 我在 Customer 表上沒有 StatusId,而是想調用 UDF 來檢索最新的日記帳條目。

CREATE Function [dbo].[CustomerStatus](
   @CustomerId BIGINT
)
RETURNS BIGINT
BEGIN
    DECLARE @StatusID BIGINT

    SELECT  
        TOP 1
        @StatusID = [StatusId]
    FROM
        [dbo].[CustomerJournal] WITH (NOLOCK)
    WHERE
        [CustomerId] = @CustomerID
    AND
    ORDER BY
        [RowID] DESC
    
    RETURN @StatusID

END

如何將屬性“狀態”添加到我的配置 class 中,它將我的 Id 傳遞到此 UDF 並檢索它?

謝謝

您可以將計算列添加到表中並使用它:

public class Customer{
    public long Id{ get; private set; }
    public string name{ get; private set; }
    public long status{ get; private set; }
    public long LastJournalEntryId {get;set;}
}

//configuration
public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
    public void Configure(EntityTypeBuilder<Customer> builder)
    {
        builder.ToTable("Customer");

        builder.HasKey(e => e.Id);

        builder.Property(e => e.Id)
            .HasColumnName("Id")
            .ValueGeneratedNever()
            .IsRequired();

        builder.Property(e => e.name)
            .HasColumnName("name")
            .IsRequired();

        //"GetLastJournalEntryIdForCustomer" is the name of your UDF
        builder.Property(e => e.LastJournalEntryId)
            .HasComputedColumnSql("GetLastJournalEntryIdForCustomer(Id)");
    }
}

根據您使用的是 Code-First 還是 DB-First,您當然首先需要在適當的位置創建它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM