首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >存储值的C#实体框架返回空异常

存储值的C#实体框架返回空异常
EN

Stack Overflow用户
提问于 2013-06-24 11:33:06
回答 1查看 405关注 0票数 0

下面是我的代码:

代码语言:javascript
复制
        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: object reference not set to a Object instance。

CRUD类文件(局部):

代码语言:javascript
复制
  public void Insert(Model.crossword exe)
    {
        context.crosswords.AddObject(exe);
    }
public void Save()
    {
        context.SaveChanges();
    }
EN

回答 1

Stack Overflow用户

发布于 2013-06-24 13:04:17

我不知道您认为这两个语句在做什么,但它可能不是您认为的那样。

代码语言:javascript
复制
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,在另一个中分配文本。这可能也不是您想要的。更有可能的是,您只想这样做:

代码语言:javascript
复制
if (!string.IsNullOrEmpty(textbox.Text))
{
    Model.crossword insert = new Model.crossword();
    insert.TextBoxID = textbox.ID;                      
    insert.TextBoxValue = textbox.Text;
    daoCrossword.Insert(insert);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17267662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档