Search code examples
c#entity-framework-6code-first

How to create list from two joined tables when foreign key is not required but still need to get all records


I have a simple DB structure. Navigation property to Owner class, and I meet a problem when I am trying to creat transport list with added OwnerName from Owner because OwnerID in Transport is not required...

public Transport()
{
        [Key]
        public int TransportID { get; set; }
        public string PlateNo { get; set; }
        public string Brand { get; set; }
        public string OwnerID { get; set; }
        [ForeignKey("OwnerID")]
        public virtual Owner Owner { get; set;} 

        [NotMapped]
        public string OwnerName { get; set; }
 } 

public partial class Owner
 {
        [Key]
        public string OwnerID { get; set; }
        public string OwnerName { get; set; }
 }

var result = (from n in Transports select new Transport()
 {TransportID=n.TransportID,
  OwnerID = n.OwnerID, 
  OwnerName = n.Owner.OwnerID
 }).ToList();

While executing query I get System.NullReferenceException: "Object reference not set to an instance of an object." I need a transport list event if it doesn't have Owner...


Solution

  •  var result = (from n in transports
                              select new Transport()
                              {
                                  TransportID = n.TransportID,
                                  OwnerID = n.OwnerID,
                                  OwnerName = n.Owner?.OwnerName
                              }).ToList();
    

    Using Null-conditional Operator will help to avoid NRE.