.net - EF 5 Code first Entities FirstOrDefault method returns null -


this example based on programming code first ef.

please @ below classes. when personrepository calls in instantiated , insertorupdate method called null value returned. of know iquariable's fitstordefault should not return null.

what wrong here. help

    public class person {      public int personid { get; set; }     public int socialsecuritynumber { get; set; }     public string firstname { get; set; }     public string lastname { get; set; }     //public int myproperty { get; set; }     public list<lodging> primarycontactfor { get; set; }     public list<lodging> secondarycontactfor { get; set; }      public personphoto photo { get; set; } } 

photo class

    public class personphoto {     public int personid { get; set; }     public byte[] photo { get; set; }     public string caption { get; set; }     public person photoof { get; set; } } 

dbcontext class

    public class domaincontext:dbcontext,idisposable {     public domaincontext(string connectionstring):base(connectionstring)     {      }      public dbset<person> people { get; set; }      protected override void dispose(bool disposing)     {         base.dispose(disposing);     }      protected override void onmodelcreating(dbmodelbuilder modelbuilder)     {          modelbuilder.entity<personphoto>()             .haskey(p => p.personid);          modelbuilder.entity<personphoto>()             .hasrequired(p => p.photoof)             .withrequireddependent(p => p.photo);       } } 

repository class

        public class personrepository     {          public personrepository()         {         }         public void  insertorupdate()         {           using(        domaincontext ctx = new domaincontext())           {             var person= ctx.people.include("photo").firstordefault();             person.firstname="pnikey";             if(person.photo==null)             {                 person.photo= new personphoto{photo=new byte[]{0}};             }             ctx.savechanges();           }         }     } 

iqueryable.firstordefault() can, , indeed designed return null if result nullable. i'm not sure why think can't, because that's primary difference between first() , firstordefault()

the "default" part means returns default type (ie. default(t)) if there no result, , since default(t) reference type null, that's returns.

if did this, return 0 rather null, because int value type , default value of int 0:

var x = new[] {1, 2, 3};  return x.firstordefault(y => y == 4); 

but since person reference type, if there no result, default type null.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -