2013-06-24 69 views
0

这里是我的代码:C#实体框架存储的值返回null例外

 protected void btnShow_Click(object sender, EventArgs e) 
    { 

     foreach (Control control in Panel1.Controls) 
     { 
      var textBox = control as TextBox; 
      if (textBox != null) 
      { 
       if (string.IsNullOrEmpty(textBox.Text)) 
       { 

       textBox.Style["visibility"] = "hidden"; 
       } 

       // textBox.Enabled = false; 

       var id = from t in textBox.Text 
          where t != null 
          select textBox.ID; 

       var text = from t in textBox.Text 
          where t != null 
          select t; 

       foreach (var x in id) 
       { 
        Model.crossword insert = new Model.crossword(); 
        insert.TextBoxID = x;      
        daoCrossword.Insert(insert); 
       } 

       foreach (var a in text) 
       { 
        Model.crossword insert = new Model.crossword(); 
        insert.TextBoxValue = a.ToString(); 
        daoCrossword.Insert(insert); 
       } 
       daoCrossword.Save();     
      }    
     } 
    } 

daoCrossword是有它的CRUD代码的类文件,我使用EF要做到这一点,我是新来的这一点,给我一个错误:System.NullReferenceException:对象引用未设置为对象的实例。

CRUD类文件(部分):

public void Insert(Model.crossword exe) 
    { 
     context.crosswords.AddObject(exe); 
    } 
public void Save() 
    { 
     context.SaveChanges(); 
    } 
+0

你在哪里得到错误?你尝试过调试吗?你的变量在错误发生时包含什么值? –

+0

我做过调试,x和a包含值,daoCrossword.Save()中的错误行;和context.crosswords.AddObject(exe);这是我的CRUD类文件 – user2376998

+0

我已经编辑在上面,包括我的类文件 – user2376998

回答

0

我不知道你在想什么你与这两个语句做,但它可能不是你认为它是。

var id = from t in textBox.Text 
     where t != null 
     select textBox.ID; 

var text = from t in textBox.Text 
      where t != null 
      select t; 

然后,您的foreach语句真的没有意义,因为您只会在集合中有一个项目。看起来好像你只是在文本框中存在某些东西时才保存数据,为此你应该只做一个简单的if语句。

接下来,在每个的foreach创建新的填字游戏的对象,但你只能在一个指定的ID,并在其他文本..这是也可能不是你想要的。更可能的是,你只是想这样做:

if (!string.IsNullOrEmpty(textbox.Text)) 
{ 
    Model.crossword insert = new Model.crossword(); 
    insert.TextBoxID = textbox.ID;      
    insert.TextBoxValue = textbox.Text; 
    daoCrossword.Insert(insert); 
} 
+0

我有很多文本框,并在2个LINQ语句是让文本框和文本框的id的值,因为我要去把它们保存到数据库 – user2376998

+0

@ user2376998 - 是的,你的foreach所控制对象获得所有这些文本框。 linq的陈述是不必要的,不会做你认为他们做的事情。正如所写,它们只能在单个文本框控件上操作。 –

+0

呵呵确定这个foreach控件。但我想你的代码,但它仍然给了我同样的错误 – user2376998