如何使用Entity Framework管理GetDate()

Rod*_*son 19 entity-framework sql-server-2008

我在我的一个数据库表中有一个这样的列

DateCreated, datetime, default(GetDate()), not null
Run Code Online (Sandbox Code Playgroud)

我试图使用实体框架在这个表上插入这样的...

        PlaygroundEntities context = new PlaygroundEntities();

        Person p = new Person
        {
            Status = PersonStatus.Alive,
            BirthDate = new DateTime(1982,3,18),
            Name = "Joe Smith"
        };

        context.AddToPeople(p);
        context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,我收到以下错误

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated.
Run Code Online (Sandbox Code Playgroud)

所以我尝试将StoreGeneratedPattern设置为计算...同样的事情,然后身份......同样的事情.有任何想法吗?

Ken*_*rdt 9

您必须手动编辑edmx xml并将SSDL StoreGeneratedPattern属性设置为identity或computed.但是,每当您通过设计器更新edmx时,您的更改都将被覆盖.

这是一个已知的问题.有关详细信息,请参阅以下链接:

Microsoft Connect Ticket

在实体框架4中使用GUID作为EntityKey


小智 5

我有同样的问题!对我来说,它是这样工作的:

数据库 MS SQL Server express:

[RowTime]  [datetime2](7)  NOT NULL

ALTER TABLE [dbo].[Table_1] ADD  CONSTRAINT [DF_Table_1_RowTime]  DEFAULT (getdate()) FOR [RowTime]
GO
Run Code Online (Sandbox Code Playgroud)

然后我将表从数据库导入到我的实体模型。实体不会实现默认值!因此,您必须将列的 StoreGeneratedPattern 设置为 Computed。然后实体将不再在那里放置任何默认值。

的组合:

datetime2,
NOT NULL, 
StoreGeneratedPattern=Computed
Run Code Online (Sandbox Code Playgroud)

为我工作!


小智 2

将 DateCreated 的类型更改为 datetime2 可能会解决该问题。

日期时间 2007-05-08 12:35:29.123

日期时间2 2007-05-08 12:35:29。12345

参考:http://technet.microsoft.com/en-us/library/bb677335.aspx67

  • 我有这个确切的问题,你能写一个正确的答案吗 wcpro? (2认同)