EF Quetioner
EF Quetioner

Reputation: 31

Entity Framework 4.0 POCO and Many-to-Many problem

I have created POCO domain objects that map to the entities in the entity domain model. Everything was working fine until now when I have to work with the many-to-many relationship.

Let's say I have three tables.
- Blog
- BlogTag
- Tag

You can see that Blogs and Tags are many-to-many with a bridge table, BlogTag that contains a foreign key to both tables.

I also have corresponding domain models:
- Blogs
- BlogsTags
- Tags

Now, I select a list of blogs and I'm trying to access a particular tag from a blog.

myBlog.BlogsTags[0].Tag

BlogTags[0].TagForeignKey is filled in, but BlogTags[0].Tag is null !!

I also have LazyLoading turned on.

What could I be doing wrong?

Thanks.

Okay. Here's some source code.

my context class

public class MyContext : ObjectContext
    {
        public MyContext() : base(Utility.GetConnectionString(...), "containerName")
        {
            Blogs = CreateObjectSet<Blog>();
            BlogsTags = CreateObjectSet<BlogTag>();
            Tags = CreateObjectSet<Tags>();

            base.ContextOptions.LazyLoadingEnabled = true;
        }

        public ObjectSet<Blog> Blogs { get; private set; }
        public ObjectSet<BlogTag> BlogsTags { get; private set; }
        public ObjectSet<Tags> Tags { get; private set; }
    }

and my poco classes just have a list of related objects with the virtual keyword.

Upvotes: 3

Views: 3091

Answers (2)

Jay
Jay

Reputation: 2703

Be sure that the relationship properties that you are accessing in the Entity are defined as "virtual" otherwise they will not be traversed automatically.

I had the same problem...eg. of my user entity:

public class User : EntityBase
    {
        public int UserID { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public virtual List<Role> Roles { get; set; } //VIRTUAL here is KEY!
}

I assume your's should be:

 public class Blog
        {

     public string Owner { get; set; }
     public string BlogText { get; set; }
     public virtual List<BlogTag> BlogTags { get; set; }  //VIRTUAL here is KEY!

    }

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292345

BlogTag shouldn't be an entity at all : it is only a relationship, it doesn't contain any actual data. If the relationship is properly modeled in your database using foreign keys, the Entity Model designer should realize that and eliminate BlogTag from the conceptual model...


EDIT:

I'm not sure why lazy loading doesn't work here, but you could always use Include to load the Tag explicitly :

var myBlog = context.Blogs.Include("BlogTags.Tag").First(b => b.Id = blogId);
var tag = myBlog.BlogsTags[0].Tag;

Upvotes: 2

Related Questions