代码之家  ›  专栏  ›  技术社区  ›  Shayne

使用EntityDataSoruce和nullable列。如何将db中的update列设置为null?

  •  0
  • Shayne  · 技术社区  · 14 年前

    当绑定到任何控件(如“FormView”)时,是否有人能够可靠地获取EntityDataSource以将可为null的列作为“null”保存到数据库中?

    我试过使用几个不同的UpdateParameters(SessionParameter、controlParameter、Parameter等)。我尝试过将“ConvertEmptyStringToNull”设置为true,并将属性完全关闭。什么都不管用。在我的“Inserts”中,它工作得很好(但显然,要插入一个记录,如果没有值,它必须插入“something”)

    我已尝试将该列绑定到标签,并将标签的文本值设置为“”。

    在所有这些情况下,我可以成功地将列设置为值,而不是设置为NULL。

    1 回复  |  直到 14 年前
        1
  •  1
  •   Nifle Hassan Syed    14 年前

    我找到的唯一解决方法是在ItemUpdated事件中重新加载对象。检查我想要设置为null的值是否为null,如果是这样,请手动再次将该值设置为null。就像这样:

    protected void FormView1_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
        {
            // Use the Exception property to determine whether an exception
            // occurred during the insert operation.
            if (e.Exception != null)
            {
                // handle the exception
            }
            else
            {
                //force the suppression of the foreign key relation
                using (var context = new ProxiEntities())
                {
                    //reload my object
                    var id = Convert.ToInt32(e.Keys["SessionID"]);
                    var session = (from o in context.Sessions
                                   where o.SessionID == id
                                   select o).FirstOrDefault();
    
                    try
                    {
                        //check if I wanted to set a value to null
                        if (e.NewValues["MagasinID"] == null)
                        {
                            //if yes, set it to null and save
                            session.MagasinID = null;
                        }
                        if (e.NewValues["LieuID"] == null)
                        {
                            session.LieuID = null;
                        }
                        context.SaveChanges();
                    }
                    catch (Exception)
                    {
                        //Add code to log the error.
                    }
                }
            }
        }
    

    这是我唯一能找到解决问题的方法。而且这似乎是一个不寻常的问题。你是我唯一能找到的人。

    推荐文章