2016-07-07 17 views
1

我一直在过去3天编码不停,现在我碰到了这个。从文本框中设置2个变量的文本。这让我很生气。该代码在编辑项目(字段不为空)时起作用,在添加一个字段时(这两个字段为空)它不起作用。设置字段为新的实体不工作 - EntityFramework

我曾尝试: - 我使用.ToString()方法,因为它没有任何不正常工作尝试。

的代码是让我为难的部分:

proiect.titlu = projectTitleTb.Text.ToString(); 
proiect.descriere = projectDescTb.Text.ToString(); 

enter image description here

我需要一个答案,这很糟糕,因为我的时间不多了,我都不敢相信这样的事情正在使很多时间。
编辑: Before and after running the code for different case

编辑:
我觉得这可能是由differencies对象类型之间造成的:当编辑时,对象类型是

{} System.Data.Entity.DynamicProxies.proiecte_BFF409556A583A0C9542252D0669E388052C2AB6DA93A2EE4C48CBFB216E8114,

而添加它的类型是简单proiecte。变量被存储在视图状态:

proiecte proiect 
    { 
     get 
     { 
      if (ViewState["proiect"] == null) 
      { 
       return new proiecte(); 
      } 
      return ViewState["proiect"] as proiecte; 
     } 
     set 
     { 
      ViewState["proiect"] = value; 
     } 
    } 

这是编辑当对象被分配: PROIECT = ProiecteDB.getById(id_proiect);
这是函数getById

public static dynamic getById(int id) 
    { 
     var db = new firma_itEntities(); 
     var query = (from p in db.proiectes 
        where p.id_proiect == id 
        select p).FirstOrDefault(); 
     return query; 
    } 

当对象被加入,而不是编辑,它不查询数据库,所以它只是创建用途 返回新proiecte();

这是类:

[Serializable] 
    public partial class proiecte 
    { 
     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",  "CA2214:DoNotCallOverridableMethodsInConstructors")] 
     public proiecte() 
     { 
      this.tasks = new HashSet<task>(); 
     } 

     public int id_proiect { get; set; } 
     public string descriere { get; set; } 
     public string status { get; set; } 
     public string titlu { get; set; } 
     public string disponibil_resurse { get; set; } 

     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] 
     public virtual ICollection<task> tasks { get; set; } 
    } 
+1

不可能没有更多的代码说,但你的类setter方法titlu和descriere为了? – Esko

+0

是的......正如我所提到的,代码在预定义变量(使用数据库中的值)时起作用,当值最初为空时它不起作用,但这不应该成为C# –

+0

您提供的代码片段似乎是按顺序排列的,所以问题在其他地方。我们只能猜测没有更多代码的地方。 – Esko

回答

-1

我希望,你已经设置了变量“titlu”,并在您的项目“descriere”的属性。

请问您可以发布上述代码。

+0

这是一条评论,而不是一个答案。 – Esko

+0

public string descriere {get;组; } public string titlu {get;组; } 这些类是由实体框架从数据库模型生成的 –

0

好显然我解决了这个问题通过创建一个新的对象中,我设置相应属性:

proiecte proiect = new proiecte 
        { 
         titlu = projectTitleTb.Text, 
         descriere = projectDescTb.Text, 
         status = "draft", 
         tasks = tasks 
        };