配置与计算列的 fk 关系 Entity Framework

Configure fk relations with computed columns Entity Framework

我有一个包含计算列的数据库模型。基本思想是,当我将一个新的 Gauge 插入 table 时,一个新的 Reading 会先自动插入另一个 table。 table Gauges 有一个计算列(或准确地说是几个),它获取最新的 Reading 的日期。

当我有一个用作外键的 INT 字段时,这一切都很好。现在范围越来越大,我不能再依赖那个领域是独一无二的,所以我需要改变 FK。

首先我尝试使用 Gauge.Id 属性,这将是理想的,因为它是 table 中的主键。问题是 Id 是在数据库中生成的,因此不知道何时插入第一个 Reading。还尝试在模型中添加另一个 Guid 属性 并将其用作 FK,但也没有成功。我还尝试在插入之前检查数据库中最大的 Id 值,并在创建时将其分配给新的 Gauge ,但也没有运气。不幸的是,我不记得为了更好地阐明每次尝试的问题而进行的所有试错组合。

我正在使用 Entity Framework 6 代码优先。

对象模型是:

public class Gauge
{
    public int Id { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime CurrentReadingDate { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public decimal CurrentReading { get; set; }
}

public class GaugeReading
{
    public int Id { get; set; }
    public int GaugeId { get; set; }
}

数据库:

[dbo].[Gauges]
[Id]                    INT              IDENTITY (1, 1) NOT NULL,
[CurrentReadingDate]    AS               ([dbo].[CurrentReadingDate]([Id])),
[CurrentReading]        AS               ([dbo].[CurrentReading]([Id]))

[dbo].[GaugeReadings]
[Id]          INT              IDENTITY (1, 1) NOT NULL,
[GaugeId]     INT              NOT NULL,
[ReadingDate] DATETIME         NOT NULL,
[Reading]     DECIMAL (18, 2)  NOT NULL,

函数:

CREATE FUNCTION [dbo].[CurrentReadingDate]
(
    @id int
)
RETURNS DATE
AS
BEGIN
    RETURN (SELECT MAX(GaugeReadings.ReadingDate) 
            FROM GaugeReadings 
            WHERE dbo.GaugeReadings.GaugeId = @id)
END

问题是:如何配置Entity Framework(和数据库)能够插入一个Gauge,初始值为Reading 以便计算列工作?或者 EF 中是否有不同的插入方法允许这样的事情?抱歉这个冗长的问题。

编辑 我在使用 Gauge.Id 作为 FK 时遇到的错误:

System.Data.Entity.Core.UpdateException: A null store-generated value was returned for a non-nullable member 'CurrentReadingDate' of type 'Repository.Gauge'.

我认为问题出在你的功能上。检查 table 中是否不存在任何行,return 某些默认日期是 db 允许的最小日期。