在Entity框架中,如何在多对多关系中按id查询



我有类似的集团实体

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

我有像这样的标签实体

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

我绘制了

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; }
}

那么如何逐组检索和逐标签检索呢?

如果你使用的是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; }
}

如果你已经创建了dbcontext,你可以通过groupId 获得一个组

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

同样的方法你可以得到一个标签

最新更新