简体   繁体   English

如何在实体框架中的多对多关系中按 id 查询?

[英]How to query by id in many to many relationship in Entity framework?

I have Group entity like我有像这样的集团实体

public class Group
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string CategoryId { get; set; }
        public ICollection<GroupTag> TagsLink { get; set; }
    }

I have Tag entity like我有像这样的标签实体

 public class Tag
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public ICollection<GroupTag> GroupLink { get; set; }
    }

and I mapped我映射了

 public class GroupTag
    {
        public string GroupId { get; set; }
        public Group Group { get; set; }
        public string TagId { get; set; }
        public Tag Tag { get; set; }
        public byte Order { get; set; }
    }

and so how to retrieve group by groupId and tag by tagId?那么如何通过 groupId 检索 group 并通过 tagId 进行标记?

if you are using net core 5 or 6 you can add some more extension to your classes:如果您使用的是 net core 5 或 6,您可以为您的类添加更多扩展:

public class Group
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public ICollection<GroupTag> GroupTags { get; set; }
        
         public string CategoryId { get; set; }
          public virtual Category Category { get; set; }

         public  virtual ICollection<Tag> Tags { get; set; }
    }

 public class Tag
    {
        public string Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<GroupTag> GroupTags { get; set; }
        
        public virtual ICollection<Group> Groups { get; set; }
    }

If you already created dbcontext you can get a group by groupId如果您已经创建了 dbcontext,您可以通过 groupId 获取一个组

var group= context.Groups
 .Include(i=> i.Tags) // if you don't need tags, ommit this
 .FirstOrDefault(i=> i.GroupId==groupId);

and the same way you can get a tag同样的方式你可以得到一个标签

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM