我正在寫一個wpf應用程序。我有一個本地數據庫(sqlCE)和兩個對應於不同表的實體類。第一個類是Account,第二個是Movements。這兩張表之間存在一對多的關係:一個賬戶可以有更多的變動。 這裏是Account類:linq2sql在數據庫中插入數據一對多的關係
[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,表名= Account]。
任何人都可以幫到我嗎?
你說「我得到一個sql異常!」 - 它是什麼 - 它們通常很具描述性 –
爲什麼你只需使用Entity Framework就可以編寫所有這些代碼? –
我正在寫wpf,但後來我想創建一個wp7應用程序。 –