1. 程式人生 > >.ef core 多對對關系的關聯方法

.ef core 多對對關系的關聯方法

url name 實體 cor table namespace color content totable

最近在使用.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 多對對關系的關聯方法