[英]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.