POCO Entity Framework 4.0 and Many-to-Many Issues

I created POCO domain objects that map to objects in the entity domain model. Everything has worked fine so far when I have to work with many-to-many relationships.

Say I have three tables.
  - Blog
  - BlogTag
  - Tag

You can see that blogs and tags are many to many with a bridge table, BlogTag, which contains a foreign key for both tables.

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

Now I select a list of blogs and I am trying to access a specific tag from a blog.

myBlog.BlogsTags [0] .tag

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

I also have LazyLoading enabled.

What can i do wrong?

Thanks.

Good. Here are some source codes.

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.

+3
source share
2 answers

BlogTag should not be an entity at all: it is only a relationship, it does not contain any real data. If the relationship is correctly modeled in your database using foreign keys, the Entity model designer should understand this and exclude BlogTag from the conceptual model ...


EDIT:

, , Include Tag :

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

, , 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!
}

, :

 public class Blog
        {

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

    }
0

Source: https://habr.com/ru/post/1725761/


All Articles