实体框架间歇性地将字节字段设置为255

时间:2016-08-08 00:36:48

标签: entity-framework entity-framework-6

我有一段插入表格的代码。简单地说,我有一个结构表

表1

  • Id int PK
  • 输入tinyint
  • 状态tinyint

在我们的PROD中挖掘之后,我观察到当值应该在(1-3)范围内时,EF可能会间歇性地将值默认为255。我理解255是SQL Server中tinyint的最大值,但我在表定义和EDMX中都没有默认值。

用法:

//OUTAGE_TYPE
public enum OUTAGE_TYPE
{
        Unknown = -1,
        SwitchingPlan = 1,
        PlannedIncident = 2,
        UnplannedIncident = 3
}

//CREATE INSTANCE
var outage = new Outage
        {
            OutageTypeId = (byte)OUTAGE_TYPE.SwitchingPlan,
            OutageStatusId = (byte)OUTAGE_STATUS.Approved,
            IncidentRID = incident.RID,
            WorkRID = incident.WorkRID,
            ETR = incident.ETR,
            DateInserted = Time.Now(),
            DateUpdated = Time.Now()
        };

捕获的SQL:

INSERT [dbo].[Outage]([OutageTypeId], [OutageStatusId], [IncidentRID], [WorkRID], [ETR], [DateInserted], [DateUpdated])
VALUES (@0, @1, @2, NULL, @3, @4, @5)
SELECT [Id]
FROM [dbo].[Outage]
WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()
-- @0: '255' (Type = Byte, Size = 1)
-- @1: '1' (Type = Byte, Size = 1)
-- @2: 'INC 11000700' (Type = String, Size = 255)
-- @3: '05-08-2016 10:05:52' (Type = DateTime2)
-- @4: '05-08-2016 22:05:22' (Type = DateTime2)
-- @5: '05-08-2016 22:05:22' (Type = DateTime2)
-- Executing at 06-08-2016 00:06:00 +02:00

错误:

  

INSERT语句与FOREIGN KEY约束冲突" FK_Outage_OutageType"。冲突发生在数据库" ONSP",表" dbo.OutageType",列' Id'。

我无法在我的本地机器上重现,也许你们之前已经经历过这种情况。非常感谢。

1 个答案:

答案 0 :(得分:1)

在我的同事和我四处寻找之后,我们找到了这个问题的根本原因。 第一个-1,不是一个字节的有效值,直接转换不会抛出异常但会产生byte.MaxValue

void Main()
{
    var type = OUTAGE_TYPE.Unknown;
    var result = (byte)type;

    //result = 255!!!
    Console.WriteLine(result);
}

public enum OUTAGE_TYPE
{
       Unknown = -1,
       SwitchingPlan = 1,
       PlannedIncident = 2,
       UnplannedIncident = 3
}