由于关系实体,更新实体框架实体失败

时间:2015-12-03 11:50:01

标签: entity-framework

我有这种结构。

Question ---< Answer
--------      ------
Id            Id
Text          Value

我尝试通过IdDbContext设置值到新的值然后调用SaveChanges来更新Answer的值。

这是失败的说明需要提问。我在虚拟Answer上有导航属性。

出于某种原因,EF认为我希望问题为空。如果我设置一个断点并延迟加载问题,那么一切正常。

我只想更新价值,我是否需要急切加载问题? 如果是这样,这对我来说似乎很奇怪。

附录

答案实体中的问题有[Required]数据注释似乎导致问题。

1 个答案:

答案 0 :(得分:2)

是的,那是怎么回事。如果导航属性不可为空,则在加载之前保存将失败。你有两个解决方案:

  1. 如果您有导航属性/* * Get cities based on city name and radius in KM */ // get geocode object as array from The Google Maps Geocoding API $geocodeObject = json_decode(file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address={CITY NAME},{COUNTRY CODE}'), true); // get latitude and longitude from geocode object $latitude = $geocodeObject['results'][0]['geometry']['location']['lat']; $longitude = $geocodeObject['results'][0]['geometry']['location']['lng']; // set request options $responseStyle = 'short'; // the length of the response $citySize = 'cities15000'; // the minimal number of citizens a city must have $radius = 30; // the radius in KM $maxRows = 30; // the maximum number of rows to retrieve $username = '{YOUR USERNAME}'; // the username of your GeoNames account // get nearby cities based on range as array from The GeoNames API $nearbyCities = json_decode(file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat='.$latitude.'&lng='.$longitude.'&style='.$responseStyle.'&cities='.$citySize.'&radius='.$radius.'&maxRows='.$maxRows.'&username='.$username, true)); // foreach nearby city get city details foreach($nearbyCities->geonames as $cityDetails) { // do something per nearby city } 您还应该添加virtual Question Question { get; set; },这样当您加载int QuestionID { get; set; }时,您将设置QuestionID值,这意味着您的问题可以为空,因为QuestionID信息已足够。
  2. 如果您没有Answer并拥有context.Entry(entityToUpdate).State = EntityState.Modified;,那么当您在context.Configuration.AutoDetectChangesEnabled = true;上更改内容时,保存更改只会更新已更改的值,而不会更新其他值,因此null属性不会有问题。
相关问题