[英]linq2sql insert data in database one-to-many relationship
我正在写一个wpf应用程序。 我有一个本地数据库(sqlCE),其中包含两个对应于不同表的实体类。 第一类是Account,第二类是Movements。 这两个表之间存在一对多的关系:一个帐户可以有更多的变动。 这是帐户类别:
[Table]
public class Account
{
.....other private fields...
private Int16 iDA;
private EntitySet<Movement> movements;
...other properties with column attribute....
//primary key
[Column(IsPrimaryKey = true, Storage="iDA", IsDbGenerated = true, AutoSync = AutoSync.OnInsert, DbType = "smallint")]
public Int16 IDA
{
get { return iDA; }
private set { iDA = value; }
}
//association
[Association(Storage = "movements", OtherKey = "IDA")]
public EntitySet<Movement> Movements
{
get { return movements; }
set { this.movements.Assign(value); }
}
public Account()
{
this.movements = new EntitySet<Movement>();
}
}
这是运动课:
[Table]
public class Movement
{
...other fields...
private Int16 iDA;
private int iDM;
private EntityRef<Account> myAcc;
//primary key
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert, DbType = "int NOT NULL IDENTITY", Storage = "iDM")]
public int IDM
{
get { return iDM; }
set { iDM = value; }
}
//property links the two tables
[Column(DbType = "smallint", Storage="iDA", isPrimaryKey=true)]
public Int16 IDA
{
get { return iDA; }
set { iDA = value; }
}
//association
[Association(Storage = "myAcc", ThisKey = "IDA")]
public Account MyAccount
{
get { return this.myAcc.Entity; }
set { this.myAcc.Entity = value; }
}
......
public Movement()
{
this.myAcc = new EntityRef<Account>();
}
}
我定义了IDA属性来链接两个表。 之后,我编写datacontext类:
public class DataBase : DataContext
{
public Table<Account> AccountTable
{
get { return this.GetTable<Account>(); }
}
public Table<Movement> MovementTable
{
get { return this.GetTable<Movement>(); }
}
public DataBase(string connection) : base(connection) { }
}
在mainclass中,我创建数据库,但是当我尝试用一个帐户对象填充数据库时,出现了sql异常! 我可以毫无问题地插入调用InsertOnSubmit(Account a)的数据,但是当我调用SubmitChanges()时,程序将停止并且异常显示“列不能包含空值。[列名称= IDA,表名称=帐户]”。
有人可以帮助我吗?
尝试对IDA字段的Column属性使用DbType = "smallint not null identity"
和CanBeNull = false
参数。
我已经解决了我的问题,在两个类中都更改了Int的IDA属性并进行了一些调整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.