【问题标题】:EF Code First in many-to-manyEF Code First 在多对多中
【发布时间】:2013-02-07 22:53:12
【问题描述】:

我有这些课程:

public class User
{
 public int Id {get; set;}
 public string Name {get; set;}
}

数据库表 - 用户

public class Pet
{
 public int Id {get; set;}
 public string Name {get; set;}
}

数据库表 - 宠物

public class UsersPets
{
 public int UserId {get; set;}
 public int PetId {get; set;}
}

数据库表 - users_pets

到现在我可以用 linq 获取用户的宠物。但是如何在 EF Code First 中自动映射 User.Pets 而无需额外的 Linq 查询?

【问题讨论】:

标签: entity-framework ef-code-first mapping many-to-many


【解决方案1】:

你不能把你的课程改成:

public class User
{
    public User(){
        Pets = new HashSet<Pet>();
    }

    public int Id {get; set;}
    public string Name {get; set;}

    public ICollection<Pet> Pets;
}

public class Pet
{
    public Pet(){
        Users = new HashSet<User>();
    }

    public int Id {get; set;}
    public string Name {get; set;}

    public ICollection<User> Users;
}

【讨论】:

    【解决方案2】:

    EF 为您创建此表,您不应该在模型中执行此操作。所以:

    public class User
    {
     public int Id {get; set;}
     public string Name  {get; set;}
    public ICollection<Pet> Pets  {get; set;}
    } 
    
    public class Pet
    {
     public int Id {get; set;}
     public string Name {get; set;}
    }
    

    将在数据库中创建附加表,您可以在代码中访问 User 实体的 Pets 集合。

    【讨论】:

      【解决方案3】:

      对于简单的多对多关系,您不需要额外的类,您只需向 UserPet 类添加两个属性:

      public class User
      {
          public int Id {get; set;}
          public string Name {get; set;}
      
          public virtual ICollection<Pet> Pets { get; set; }
      
          public User
          {
              Pets = new List<Pet>();
          }
      }
      
      public class Pet
      {
          public int Id {get; set;}
          public string Name {get; set;}
      
          public virtual ICollection<User> Users { get; set; }
      
          public Pet
          {
              Users = new List<User>();
          }
      }
      

      注意PetsUsers 集合是virtual。这将启用延迟加载,以防止在您不需要用户的宠物时加载它们。

      // Pets not loaded
      var user = db.Users.Find(1);
      
      // This loads the pets for the user (lazy loading)
      foreach (var pet in user.Pets)
      {
          ...
      }
      
      // This immediately loads the pets for the user (eager loading)
      var user2 = db.Users.Include(u => u.Pets).SingleOrDefault(u => u.Id == 2);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-20
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        相关资源
        最近更新 更多