2013-02-22 98 views
0

我有这个类:EF代码第一次在许多一对多

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

DB表 - 用户

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查询?

+1

这里看看我的导航性能文章:http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_code_first你需要描述这些实体如何使用导航属性相关。 – 2013-02-22 10:42:27

回答

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

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