EF代码优先于多对多

时间:2013-02-22 10:38:38

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

我有这个课程:

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中没有额外的Linq查询,如何自动映射User.Pets

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

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集合。

答案 2 :(得分:1)

对于简单的多对多关系,您不需要额外的类,只需向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);