【问题标题】:linq2sql insert data in database one-to-many relationshiplinq2sql 在数据库一对多关系中插入数据
【发布时间】:2013-01-12 18:27:34
【问题描述】:

我正在编写一个 wpf 应用程序。我有一个本地数据库(sqlCE),其中有两个实体类对应于不同的表。第一个类是 Account,第二个类是 Movements。两个表之间存在一对多的关系:一个帐户可以有更多的动作。 这是 Account 类:

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

在主类中我创建了数据库,但是当我尝试使用帐户对象填充它时,我得到了一个 sql 异常!我可以毫无问题地插入调用 InsertOnSubmit(Account a) 的数据,但是当我调用 SubmitChanges() 时,程序停止并且异常显示“列不能包含空值。[列名 = IDA,表名 = 账户]”。

谁能帮帮我?

【问题讨论】:

  • 你说“我得到一个 sql 异常!” - 它是什么 - 它们通常很有描述性
  • 既然可以使用实体框架,为什么还要手动编写所有这些代码?
  • 我正在用 wpf 写东西,但后来我想创建一个 wp7 应用程序。

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-05
      • 2022-01-09
      • 2021-05-04
      • 2018-12-29
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      相关资源
      最近更新 更多