首页 > 其他 > 详细

.ef core 多对对关系的关联方法

时间:2018-11-13 23:24:28      阅读:489      评论:0      收藏:0      [点我收藏+]

最近在使用.net core 重构博客是,在使用ef core连表查询时,遇到了一些问题。记录一下。

下面是实体代码

BlogEntity

namespace Blog.Service.Entities
{
    public class BlogEntity:BaseEntity
    {
        public string Title { get; set; }
        public string Content { get; set; }
        public virtual List<BlogLabelEntity> BlogLabels { get; set; } = new List<BlogLabelEntity>();
    }
}

BlogConfig

namespace Blog.Service.EntityConfig
{
    public class BlogConfig : IEntityTypeConfiguration<BlogEntity>
    {
        public void Configure(EntityTypeBuilder<BlogEntity> builder)
        {
            builder.ToTable("T_Blogs");
            builder.HasKey(u => u.Id);
            builder.Property(u => u.Title).HasMaxLength(500).IsRequired();
            builder.Property(u => u.Content).IsRequired();
            
            
        }
    }
}

Label

namespace Blog.Service.Entities
{
    public class LabelEntity:BaseEntity
    {
        public string Title { get; set; }
        public string IconUrl { get; set; }

        public virtual List<BlogLabelEntity> BlogLabels { get; set; } = new List<BlogLabelEntity>();
    }
}

LabelConfig

namespace Blog.Service.EntityConfig
{
    public class LabelConfig : IEntityTypeConfiguration<LabelEntity>
    {
        public void Configure(EntityTypeBuilder<LabelEntity> builder)
        {
            builder.ToTable("T_Labels");
            builder.HasKey(u => u.Id);
            builder.Property(u => u.Title).HasMaxLength(50).IsRequired();
            builder.Property(u => u.IconUrl).HasMaxLength(500);

        }
    }
}

BlogLabelEntity

namespace Blog.Service.Entities
{
    public class BlogLabelEntity:BaseEntity
    {
        public long BlogId { get; set; }
        public virtual BlogEntity Blog { get; set; }
        public long LabelId { get; set; }
        public virtual LabelEntity Label { get; set; }
    }
}

BlogLabelConfig

 

这里需要连接blog和label两个表

以blog为例

blogService.GetAll().Include(u => u.BlogLabels).ThenInclude(bl=>bl.Label)

以上为多对多的关联

.ef core 多对对关系的关联方法

原文:https://www.cnblogs.com/c-supreme/p/9955483.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!