ASP.NET Entity Framework 4 Navigation Entity not reflecting changes made to database
I have two database tables (NEWS and NEWS_IMAGES) that I have produced an entity model for with a one to many association made between them in the model.
However when I query the model using the Navigation property (NEWS_IMAGES) it doesn't return any recent database inserts but if I query the navigation entity itself then I get all latest changes.
First Method using Navigation property:
IEnumerable<NEWS_IMAGES> imgs = dal.NEWS.Where(n => n.NEWS_ID == NewsID).FirstOrDefault().NEWS_IMAGES;
Second method using the actual entity (returns all recent changes):
IEnumerable<NEWS_IMAGES> imgs = dal.NEWS_IMAGES.Where(i => i.News_ID == NewsID)
This is the code that inserts a record to the NEWS_IMAGES entity:
NEWS_IMAGES img = new NEWS_IMAGES
{
News_ID = newsID,
News_Image_Filename_Small = 开发者_运维知识库file_Sm,
News_Image_Filename_Medium = file_Med,
News_Image_Filename_Large = file_Lrge,
News_Image_Order = imgCnt + 1
};
dal.NEWS_IMAGES.AddObject(img);
dal.SaveChanges();
The default behavior of the EF is to load only the entity directly accessed by the application (e.g. News). IF the EF loaded all the related entities (e.g. News_Images) you will end up loading more entities than you actually need. You can uses something called eager loading to load related entities using the Include() method. In your case you will have something like this:
var imgs= dal.NEWS.Include("NEWS_IMAGES").Where(n => n.NEWS_ID == NewsID).FirstOrDefault();
You should try using the following which should do the trick:
IEnumerable<NEWS_IMAGES> imgs =
dal.NEWS.Where(n => n.NEWS_ID == NewsID).SelectMany(i => i.NEWS_IMAGES)
精彩评论