如何在c#中将自动生成的主键字段留空时插入实体对象?

时间:2014-12-01 10:56:00

标签: c# winforms entity-framework datagridview

我有一个使用实体模型的CRUD操作的winform应用程序。它适用于多个表,因此预先不知道要加载哪些数据。现在,我有一些表,其中主键由oracle自动生成。现在,当我尝试从datagridview插入数据而使主键列为空(datagridview在该列中留下0)时,它会抛出异常。我怎么解决这个问题?以下是我加载和插入数据的代码:

 StudentEntities context;
 BindingSource stBindingSource = new BindingSource();
 private void btnShowData_Click(object sender, EventArgs e)
 {
     var TableName = cboSelectTable.Text.ToString();
     dgvLoadTable.Columns.Clear();
     context = new  StudentEntities();
     var rawData = context.GetType().GetProperty(TableName).GetValue(context, null);
     var truncatedData = ((IQueryable<object>)rawData); 
     stBindingSource.DataSource = new BindingSource { DataSource = truncatedData };
     dgvLoadTable.DataSource = stBindingSource;
 } 

 private void btnSave_Click(object sender, EventArgs e)
 {
    context.SaveChanges();
 }

 void stBindingSource_AddingNew(object sender, AddingNewEventArgs e)
 {
    e.NewObject = new TABLEINFO();
    context.AddObject("StudentEntities.TABLEINFO", e.NewObject);
 }

0 个答案:

没有答案