[英]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.