我有一个名为Room的数据库表。
此表在某些列上有一些默认值:
ALTER TABLE [dbo].[Room] ADD CONSTRAINT [DF_Room_Created] DEFAULT (getdate()) FOR [Created]
GO
ALTER TABLE [dbo].[Room] ADD CONSTRAINT [DF_Room_Updated] DEFAULT (getdate()) FOR [Updated]
GO
ALTER TABLE [dbo].[Room] ADD CONSTRAINT [DF_Room_RecordStatus] DEFAULT (0) FOR [RecordStatus]该表还具有以下触发器:
ALTER TRIGGER [dbo].[RoomInsert] ON [dbo].[Room]
FOR INSERT
AS
DECLARE @PKey int, @TrackingId int
SELECT @PKey = PKey, @TrackingId = TrackingId FROM INSERTED
IF @TrackingId = 0
UPDATE Room
SET TrackingId = @PKey
WHERE PKey = @PKey我们目前正在开发一个使用Entity Framework4的MVC3Web应用程序。当我运行以下代码时,没有应用任何默认值,也没有触发触发器:
// Create the new room record
Room newRoom = new Room();
newRoom.SiteKey = parentFloor.SiteKey;
newRoom.SiteSurveyKey = parentFloor.SiteSurveyKey;
newRoom.BuildingKey = parentFloor.BuildingKey;
newRoom.FloorKey = parentFloor.PKey;
newRoom.Name = eventModel.RoomName;
newRoom.Description = eventModel.RoomName;
newRoom.CreatedBy = eventModel.UserKey;
_entities.Rooms.AddObject(newRoom);
_entities.SaveChanges();我在数据库上运行了一个概要文件,插入结果如下:
exec sp_executesql N'insert [dbo].[Room]([TrackingID], [OriginalPKey], [BuildingKey], [SiteSurveyKey], [SiteKey], [Name], [Description], [RiskColour], [CreatedBy], [Created], [Updated], [RecordStatus], [FloorKey], [DisplayOrder])
values (null, null, @0, @1, @2, @3, @4, null, @5, null, null, null, @6, null)
select [PKey]
from [dbo].[Room]
where @@ROWCOUNT > 0 and [PKey] = scope_identity()',N'@0 int,@1 int,@2 int,@3 varchar(255),@4 varchar(255),@5 int,@6 int',@0=29970,@1=20177,@2=39373,@3='Another Room ',@4='Another Room ',@5=139,@6=25454我猜测没有应用默认值是因为专门传递了NULL,并且由于sp_executesql而没有触发触发器。有什么办法可以绕过这个问题吗?
发布于 2013-02-25 19:26:59
作为@JustAnother..。说,约束将不会有什么用处,因为你总是会提供一个值,但是你的触发器应该仍然可以正常工作。
在SQL跟踪中,您将看到TrackingID的值为null。在您的触发器中,您正在测试TrackingID=0,当为TrackingID = null时,该值为false。
尝试更新触发器以测试null。
发布于 2013-02-25 19:21:18
Entity Framework不关心您的默认约束。它将始终提交一个值,只要您的列没有在EF模型中标记为Identity或Computed。当您将列更改为"Computed“时,您不能再使用entity对象更新该列,它将始终采用数据库值(以及您的默认约束值)。
发布于 2013-02-25 19:25:56
当你使用EF时,你基本上只需要接受应用程序是主程序,而不是数据库。
您应该在Room构造函数中设置默认值,而不是通过数据库默认约束(诚然,对于创建/更新日期,出于时区等原因,您可能希望在数据库中执行此操作...)
Entity Framework - Default value for property using Data Annotations
https://stackoverflow.com/questions/15065700
复制相似问题