linq2sql在数据库中插入数据的一对多关系

时间:2013-01-10 20:53:40

标签: c# wpf windows-phone-7 linq-to-sql model-associations

我正在写一个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,表名=帐户]”。< / p>

任何人都可以帮助我?

2 个答案:

答案 0 :(得分:0)

尝试使用DbType = "smallint not null identity"CanBeNull = false参数作为IDA字段的Column属性。

答案 1 :(得分:0)

我已经解决了我的问题,在Int中更改了两个类中的IDA属性并进行了一些调整。