首页 新闻 赞助 找找看

ef core 2.0 多对多 查询的问题.

0
[已解决问题] 解决于 2018-01-28 12:41
class MyContext : DbContext
    {
        public DbSet<Post> Posts { get; set; }
        public DbSet<Tag> Tags { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<PostTag>()
                .HasKey(t => new { t.PostId, t.TagId });

            modelBuilder.Entity<PostTag>()
                .HasOne(pt => pt.Post)
                .WithMany(p => p.PostTags)
                .HasForeignKey(pt => pt.PostId);

            modelBuilder.Entity<PostTag>()
                .HasOne(pt => pt.Tag)
                .WithMany(t => t.PostTags)
                .HasForeignKey(pt => pt.TagId);
        }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public List<PostTag> PostTags { get; set; }
    }

    public class Tag
    {
        public string TagId { get; set; }

        public List<PostTag> PostTags { get; set; }
    }

    public class PostTag
    {
        public int PostId { get; set; }
        public Post Post { get; set; }

        public string TagId { get; set; }
        public Tag Tag { get; set; }
    }

上面是官方的例子~~~ 我已经能正常添加了, 

但是遇到些问题~~

比如我查询

var postlist=_webContext.Posts.Include(x => x.PostTag).ToArray();

但是我在去找postlist.PostTag[0].Tag.TagID

得到的结果是NULL. PostTag对象是的确没错的. ID 也有, 但是我再去下面找 Tag对象里面的值的时候就有问题了. 请问是没加载进来吗?        这种问题应该怎么解决呢?

谢谢

我不想二次查的主要原因在于我想用Mapper一次转换过来

            CreateMap<Post, PostOutputDto>().ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.user.UserName))
                .ForMember(dest => dest.Tags, opt => opt.MapFrom(src => src.PostTag.ToList().Select(t => t.Tag).ToList()));

结果转换过来总是不对~~~有点郁闷~

< >
分享
最佳答案
0

的确需要 Include + ThenInclude

var queryPost = await readDbContext.Posts
    .Include(p => p.PostTags)
    .ThenInclude(pt => pt.Tag)
    .FirstOrDefaultAsync();

详见 初试 Entity Framework Core 的多对多映射

VS2017 对 ThenInclude 的智能感知有个 bug ,详见 Include->ThenInclude for a collection

奖励园豆:5
dudu | 高人七级 |园豆:31075 | 2018-01-28 10:23

没错~ ThenInclude 智能感知的确有BUG~

Red Cat | 园豆:16 (初学一级) | 2018-01-28 12:40
其他回答(2)
0

ThenInclude

Red Cat | 园豆:16 (初学一级) | 2018-01-27 18:13
0

你的数据加了吗

ll...ll | 园豆:233 (菜鸟二级) | 2018-01-27 19:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册