Search code examples
c#wpfwindows-phone-7linq-to-sqlmodel-associations

linq2sql insert data in database one-to-many relationship


I'm writing a wpf app. I have a local database (sqlCE) with two entity classes that correspond to different tables. The first one class is Account and the second one is Movements. There's a relationship one-to-many between the two tables: an account can have more movements. Here is Account class:

[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>();
    }
}

and here's Movement class:

[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>();
    }

}

I define IDA property to link the two tables. After that I write datacontext class:

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) { }
}

In mainclass I create database, but when i try to populate it with an account object, I get a sql exception! I can insert data calling InsertOnSubmit(Account a) without problems, but when I call SubmitChanges() the program stops and the exception says "The column can not contain null values. [Column name = IDA, Table name = Account]".

Anyone can help me?


Solution

  • I've solved my problem, changing in Int the IDA property in both classes and making some adjustment.