code first - Entity and mapping using Entity Framework 4 how to handle null (ICollection)? -


i have fellowing entity :

 public class post     {         public long postid { get; private set; }         public datetime date { get; set; }         [required]         public string subject { get; set; }         public user user { get; set; }         public category category { get; set; }         [required]         public string body { get; set; }          public virtual icollection<tag> tags { get; private set; }          public post()         {             category = new category();         }          public void attachtag(string name, user user)         {             if (tags.count(x => x.name == name) == 0)                 tags.add(new tag {                      name = name,                      user = user                  });             else                 throw new exception("tag specified name attached post.");         }          public tag deletetag(string name)         {             tag tag = tags.single(x => x.name == name);             tags.remove(tag);              return tag;         }          public bool hastags()         {             return (tags != null || tags.count > 0);         } 

the problem virtual icollection tags { get; private set; }

when there no tags inside, show null. can't initialize because need virtual.

how handle nulls in entities ? how tags initialized , ?

thanks.

you can initialize (actually must) if virtual. code generated poco t4 template:

[global::system.codedom.compiler.generatedcodeattribute("csob.arm.entitygenerator", "1.0.0.0")] public virtual icollection<transactioncodegroup> transactioncodegroups {         {         if (_transactioncodegroups == null)         {             _transactioncodegroups = new fixupcollection<transactioncodegroup>();         }         return _transactioncodegroups;     }     set     {         _transactioncodegroups = value;     } } private icollection<transactioncodegroup> _transactioncodegroups; 

as see collection initialized when getter first called.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -