Linq插入数据的问题

来源:百度知道 编辑:UC知道 时间:2024/06/05 10:14:53
比如表test,在linq中也就是当做一个对象来使用。
此表中有个主键id,int类型,自动增量。
在插入的时候不给该id赋值,但是却默认为0
导致插入失败,因为id为自动增量,不可以为其赋值。但是它是int的,默认为0.
那么该如何做呢?谢谢。

你添加记录的语句是什么?仅凭你的描述,虽然知道问题所在,但是没办法修改啊

// 补充.
你的LTS的DataContext.Designer.cs代码里id这个属性怎么定义的?
大约应该:
[Column(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._ID = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}

这个样子.你的呢?

你的描述做如下假定:
create table Test(
Id int identity(0,1) primary key,
Other nvarchar(20) null
)
var test = new Test(){Other="其它内容";}//实例化Test时不为Id赋值。
cxt.AddToTest(test);
我没用过LINQ to SQL更新数据,你的描述,在实体框架中是不存在的,我上面的做法不会有问题,在LTS中应该也可以吧。