简体   繁体   English

如何告诉EF核心两个型号使用同一个表?

[英]How to tell EF core two models use the same table?

I'm migrating a classic SQL database to EF core 2.2 and I'm facing a problem. 我正在将经典的SQL数据库迁移到EF核心2.2,我遇到了一个问题。 I'm not new to EF but I don't see how to do this... 我不是EF的新手,但我不知道怎么做......

Here is the problem, I have a table Users , a table Groups , and a table Members . 这是问题,我有一个表Users ,一个表Groups和一个表Members Members are users composing Groups. 成员是组成组的用户。 I simplified models and kept only the keys : 我简化了模型,只保留了键:

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

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

public class Member
{
    [Key]
    public int UserId { get; set; }

    [ForeignKey(nameof(UserId))]
    public virtual User User { get; set; }

    [Key]
    public int GroupId { get; set; }

    [ForeignKey(nameof(GroupId))]
    public virtual Group Group { get; set; }
}

public class Group
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public virtual ICollection<Member> Members { get; set; }
}

In classic SQL I can join tables by key, but how can I "jump" from Users to Groups like User.Groups ? 在传统的SQL我可以通过键连接表,但如何从“跳” UsersGroupsUser.Groups

User already has a groups why do you need to include the group into Member? 用户已经有一个组,为什么需要将该组包含在成员中? is not just having a user enough? 不只是让用户足够吗? If you need to read Members from DB then you can read them and use "Include" method to add User or Groups in your case. 如果您需要从DB读取成员,那么您可以阅读它们并使用“包含”方法在您的案例中添加用户或组。 Something like this will do the job: 这样的事情可以完成这项工作:

   var result = db.Members
                .Include(m => m.Groups)
                .Include(m => m.User)

Ok, I resolved this by another way : 好的,我通过另一种方式解决了这个问题

User.Groups = context.Groups.Where(g => g.Members.Any(m => m.UserId == x.Id)).Select(g => new GenericData
{
    Id = g.Id,
    Tag = g.Tag,
    Label = g.Name,
    Flag = g.Flag
}).ToList()

Where x is the db user 其中x是db用户

It works like this, but if someone could say me how to do this like I wanted at start, I'm curious to know it :) 它的工作方式是这样的,但是如果有人能像我想要的那样说我怎么做,我很想知道它:)

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

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