InvalidCastException的对LINQ-2-SQL模式当插入 [英] InvalidCastException on LINQ-2-SQL Model When Inserting

查看:100
本文介绍了InvalidCastException的对LINQ-2-SQL模式当插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个InvalidCastException试图插入一个项目将使用LINQ到SQL数据库时。据我所知,一切都是正确的类型。

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.

在SQL表(有删节):

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_Timer] PRIMARY KEY CLUSTERED 
(
    [TimerId] ASC
)

LINQ的模型(有删节):

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; }

}

和违规code为(有删节):

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
}

该错误消息说 System.InvalidCastException:指定强制转换为无效,但它没有提到该属性导致了这一问题。任何人都可以发现其属性导致我的问题?

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?

推荐答案

我的表中删除,重新创建它,刷新我的模型,一切都开始工作,而无需改变任何东西。我不认为有什么改变,但很明显,.NET又喜欢我。

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.

这篇关于InvalidCastException的对LINQ-2-SQL模式当插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆