2016-12-05 149 views
-1

如何使用Lambda EF核心更新子表值。EF核心NullReferenceException訪問相關實體

var UpdatePercentage = _context.TaskOverview.Single(c => c.Id == 100); 
UpdatePercentage.Completedpercentage = 30; 
UpdatePercentage.TaskSubInfo.Content1 = "Some value"; 

await _context.SaveChangesAsync(); 

我得到的NullReferenceException錯誤

NullReferenceException: Object reference not set to an instance of an object. 
+0

上的三行你得到你的異常:是你的_context空?或者是UpdatePercentage.CompletedPercentage null?或者也許UpdatePercentage.TaskSubInfo爲空? –

+0

可能重複[什麼是NullReferenceException,以及如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it ) – kiziu

回答

0

我猜你是在相關Entity TaskSubInfo得到NullReferenceException

EntityFramework犯規負載相關的默認Entityyou have to do it

var UpdatePercentage = _context.TaskOverview 
          .Include(to => to.TaskSubInfo) 
          .Single(c => c.Id == 100); 

UpdatePercentage?.Completedpercentage = 30; 
UpdatePercentage?.TaskSubInfo.Content1 = "Some value"; 

await _context.SaveChangesAsync(); 
+0

。包括做了伎倆謝謝 – David

0

您可以使用Include

var UpdatePercentage = _context.TaskOverview.Include("TaskSubInfo").Single(c => c.Id == 100);