我是新来的asp.net mvc和我有问题,我想我会解决它们很容易与asp.net web窗体。然而,该项目必须在mvc,所以这是问题所在。asp.net mvc 3从一对多关系的EF查询
我得到X表
table1的用户 INT USER_ID 用户名字符串
table2的好友 INT friendshipID INT USER_ID INT friend_ID
在表2中,USER_ID表示是当前用户friend_ID代表他朋友的ID。它是一对多的关系。 现在我想要做的是,在用户/细节/ ID视图中,显示该用户的所有朋友。 我想要做的查询是:首先从table2中选择friend_IDs,其中user_ID = id(来自querystring),然后从table1中选择每个用户名,其中user_ID = friend_ID。
我认为这在SQL中非常简单,但不知道如何使用mvc语法来实现。
控制器:
// // GET:/用户/细节/ 5
public ViewResult Details(int id)
{
User user = db.Users.Find(id);
return View(user);
}
的视图:
@model Social2.Models.User
<div class="display-label">Friends</div>
<div class="display-field">
@foreach (var friend in @Model.Friends)
{
@friend.User.username;
}
</div>
的视图返回错误的结果。
模型
public partial class User
{
public User()
{
this.Albums = new HashSet<Album>();
this.Friends = new HashSet<Friend>();
this.Messages = new HashSet<Message>();
this.Posts = new HashSet<Post>();
this.Groups = new HashSet<Group>();
}
public int user_ID { get; set; }
public System.Guid user_UniqueID { get; set; }
public string username { get; set; }
public virtual ICollection<Album> Albums { get; set; }
public virtual aspnet_Users aspnet_Users { get; set; }
public virtual ICollection<Friend> Friends { get; set; }
public virtual ICollection<Message> Messages { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public virtual ICollection<Group> Groups { 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; }
}
也是上下文
public partial class ASPNETDBEntities : DbContext
{
public ASPNETDBEntities()
: base("name=ASPNETDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Album> Albums { get; set; }
public DbSet<aspnet_Users> aspnet_Users { get; set; }
public DbSet<Friend> Friends { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<Message> Messages { get; set; }
public DbSet<Picture> Pictures { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<sysdiagram> sysdiagrams { get; set; }
public DbSet<User> Users { get; set; }
}
请为您正在使用的数据库访问技术的问题添加正确的标记。 “db.Users”是什么是完全不清楚的。我猜实体框架,但请准确。同时显示你的模型类。您的问题与您正在使用的数据库访问技术更相关,与ASP.NET MVC无关。 –
从模式和Find方法看起来像使用EntityFramework DbContext来访问数据库。请指定。如果是这样,尝试查询像'db.Users.Include(“Friends”)。FirstOrDefault(u => u.UserId == id);'你也没有提到你的模型类,因此查询有一些假设。 –
对不起,是的,这是EF,请参阅编辑 – Milanix