正如标题所说,我在 Asp.net mvc 3 EF 中的查询有问题。我得到了 2 个具有 1 对多关系的表。
table1 用户 int user_ID string 用户名
table2 Friends int FriendshipID int user_ID intfriend_ID
控制器:
// // 获取:/用户/详细信息/5
public ViewResult Details(int id)
{
User user = db.Users.Include("Friends").FirstOrDefault(u => u.user_ID == id);
//Also for each friend get the User:
foreach (var friend in user.Friends.ToList())
{
friend.User = db.Users.Find(friend.friend_ID);
}
return View(user);
}
视图“详细信息”:
@model Social2.Models.User
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div class="display-field">
@foreach (var friend in @Model.Friends)
{
@friend.User.username;
}
</div>
语境:
public partial class ASPNETDBEntities : DbContext
{
public ASPNETDBEntities()
: base("name=ASPNETDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<aspnet_Users> aspnet_Users { get; set; }
public DbSet<Friend> Friends { get; set; }
public DbSet<User> Users { get; set; }
}
用户模型:
public partial class User
{
public User()
{
this.Friends = new HashSet<Friend>();
}
[Key]
public int user_ID { get; set; }
public System.Guid user_UniqueID { get; set; }
public string username { get; set; }
public virtual aspnet_Users aspnet_Users { get; set; }
public virtual ICollection<Friend> Friends { get; set; }
}
朋友模型
public partial class Friend
{
public int friendship_ID { get; set; }
public int user_fr_ID { get; set; }
public int friend_ID { get; set; }
public virtual User User { get; set; }
}
问题是,当我转到 ~/user/details/1 时,视图只显示一个(最后一个)朋友。对于每个用户,它都会显示他们的最后一个朋友。如何全部展示?