Entity Framework many to many relationship doesn't work
I have a problem with using EF 4.1 and many to many relationship. I decided to use database first approach (although I got the same problem with code first approach), and I created a model of the database:
I have a many to many relationship between Picture and Tag tables. In the DB it is created as a new table called "PictureTag" with fields "Picture_Id" and "Tag_Id".
I am adding data to my database with the following piece of code:
if (tags != null)
{
foreach (HtmlNode tagNode in tags)
{
string tagString = tagNode.InnerText.Remove(0, 1);
Tag tag;
if (db.Tags.Any(q => q.TagName == tagString))
{
tag = db.Tags.Single(q =>开发者_如何转开发 q.TagName == tagString);
}
else
{
tag = new Tag { TagName = tagString };
}
pic.Tags.Add(tag);
}
}
List<DbEntityValidationResult> list = db.GetValidationErrors().ToList();
db.Pictures.Add(pic);
db.SaveChanges();
This is of course just a part of my code. It is a part of my Crawler function. The code works fine, doesn't generate any errors, and works on a single DB context.
After this function is done I am able to see data in my DB, all three pictures, tags and entities in PictureTag table.
Yet when I try to put on my view pictures, and tags that correspond to that picture, than I can't see any tags. Like none of the pictures had any tags attached to them. I know it is not true, because I see data in my DB, so I don't know what is wrong...
This is the code fr my view:
@model IEnumerable<SikSolution.Picture>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach (var item in Model)
{
<div>
<img src="@item.Link" alt="@item.Name" />
<br />
<span>
Tags: @foreach (var tag in item.Tags)
{
Html.Label(tag.TagName + ", ");
}
</span>
</div>
}
I really don't know what is wrong... I would appreciate any advice or pointing me in the right direction.
Thanks!
Possible explanation is that you don't use lazy loading and also didn't load your Picture
collection including the related tags (eager loading). It should look like this:
//...
var pictures = db.Pictures.Include("Tags") // or Include(p => p.Tags) in EF 4.1
.Where(...)
.ToList();
return View(pictures);
精彩评论