InvalidCastException on LINQ-2-SQL Model When Inserting
I am getting an InvalidCastException when trying to insert an item into a database using LINQ-to-SQL. As far as I can tell, everything is the proper type.
The SQL table is (abridged):
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_T开发者_开发技巧imer] PRIMARY KEY CLUSTERED
(
[TimerId] ASC
)
The LINQ model is (abridged):
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; }
}
And the offending code is (abridged):
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
}
The error message says System.InvalidCastException: Specified cast is not valid.
but it doesnt mention which property is causing the problem. Can anyone spot which property is causing me problems?
You might want to either:
1) Change TimeStamp data type to DateTime2 - SQL Server 2008 only.
or
2) Change timer.TimeStamp = DateTime.UtcNow;
to timer.TimeStamp = DateTime.Now.ToUniversalTime();
I dropped the table, recreated it, refreshed my model and everything started working without having to change anything else. I dont think anything changed, but clearly .NET likes me again.
I solved that problem by setting the Server Data Type
property to uniqueidentifier
in my DBML.
精彩评论