问题描述
我正在使用 Entity Framework Core 和 Fluent API 的代码优先方法,我正在尝试为一个表创建一个列,该列具有基于该表的其他列生成的值。该表还包含外键,我想用不同于其 Id 的方式表示外键(例如名为 name 的列)。
这是我目前情况的通用代码。
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
public string display { get; set; }
}
public class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
我的 OnModelCreating
中的 DbContext
如下所示:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// BOOK DeFinition
modelBuilder.Entity<Book>(entity =>
{
// Primary key
entity.HasKey(p => p.Id);
// Foreign key
entity.HasOne(v => v.Author)
.WithMany(v => v.Books)
.HasForeignKey(v => v.AuthorId);
// Properties
entity.Property(p => p.Id).ValueGeneratedOnAdd();
entity.Properties(p => p.display)
.HasComputedColumnsql("SOME sql QUERY HERE?");
// Other property deFinitions
});
// AUTHOR DeFinition
modelBuilder.Entity<Author>(entity =>
{
// Primary key
entity.HasKey(p => p.Id);
// Properties
entity.Property(p => p.Id).ValueGeneratedOnAdd();
// Other property deFinitions
});
}
从 this website 和其他人那里我了解到您可以在 HasComputedColumnsql
中使用 sql 查询。但是,我不确定如何为我的用例创建这种查询。
TLDR;
如何在 HasComputedColumnsql
的 sql 查询中使用外键,将列的计算值设置为引用表(由外键引用)中的列值。
解决方法
您不能引用另一个表,这不是计算列的工作方式。一种方法是创建一个标量函数并调用它。例如:
CREATE FUNCTION dbo.MySuperFunction (@value INT)
RETURNS INT AS
BEGIN
-- do stuff with other tables
RETURN @value*2
END
在您的 C# 代码中:
entity.Properties(p => p.Display)
.HasComputedColumnSql("dbo.MySuperFunction([AuthorId])");