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()));
结果转换过来总是不对~~~有点郁闷~
的确需要 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
没错~ ThenInclude 智能感知的确有BUG~
ThenInclude
你的数据加了吗