0

我有这个课程:

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

DB 表 -宠物

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

数据库表 - users_pets

到现在我可以用 linq 获取用户的宠物。User.Pets但是在 EF Code First 中如何在没有额外 Linq 查询的情况下进行自动映射?

4

3 回答 3

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;
}
于 2013-02-22T11:18:09.350 回答
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;}
}

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

于 2013-02-22T14:22:28.763 回答
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);
于 2013-02-22T14:32:24.423 回答