尝试使用LINQ-to-SQL将项插入数据库时,我收到InvalidCastException。据我所知,一切都是正确的类型。
SQL表是(删节):
CREATE TABLE [dbo].[Timer](
[TimerId] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](64) NOT NULL,
[TimeStamp] [datetime] NOT NULL,
[SessionId] [uniqueidentifier] NOT NULL,
[Action] [nvarchar](50) NOT NULL,
[ActionId] [uniqueidentifier] NOT NULL,
[Description] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_Timer] PRIMARY KEY CLUSTERED
(
[TimerId] ASC
)
LINQ模型是(删节):
public partial class Timer
{
[Column(AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int TimerId { get; set; }
[Column(DbType = "NVarChar(64) NOT NULL", CanBeNull = false)]
public string UserName { get; set; }
[Column(DbType = "DateTime NOT NULL")]
public DateTime TimeStamp { get; set; }
[Column(DbType = "UniqueIdentifier NOT NULL")]
public Guid SessionId { get; set; }
[Column(DbType = "NVarChar(50) NOT NULL", CanBeNull = false)]
public string Action { get; set; }
[Column(DbType = "UniqueIdentifier NOT NULL")]
public Guid ActionId { get; set; }
[Column(DbType = "NVarChar(256) NOT NULL", CanBeNull = false)]
public string Description { get; set; }
}
违规代码是(删节):
using (var ctx = new MyDataContext())
{
var timer = new Timer();
timer.Action = "Start";
timer.ActionId = Guid.NewGuid();
timer.Description = "foo";
timer.SessionId = Guid.NewGuid();
timer.TimeStamp = DateTime.UtcNow;
timer.UserName = "foo";
ctx.Timers.InsertOnSubmit(timer);
ctx.SubmitChanges(); // exception thrown here
}
错误消息显示System.InvalidCastException: Specified cast is not valid.
,但它没有提到导致问题的属性。谁能发现哪个房产给我带来了问题?
答案 0 :(得分:0)
您可能想要:
1)将TimeStamp数据类型更改为DateTime2 - 仅限SQL Server 2008。
或
2)将timer.TimeStamp = DateTime.UtcNow;
更改为timer.TimeStamp = DateTime.Now.ToUniversalTime();
答案 1 :(得分:0)
我放下桌子,重新创建它,刷新我的模型,一切都开始工作而不必改变任何其他东西。我不认为有任何改变,但显然.NET再次喜欢我。
答案 2 :(得分:0)
我通过在我的DBML中将Server Data Type
属性设置为uniqueidentifier
来解决了这个问题。