0
我正在開發使用MVC原型平臺,用戶可以在其中作一簡介,並使用個人資料,以文字的帖子,喜歡的社交媒體網站的列表。我在我的數據庫中的以下兩個表:填充使用外鍵值在MVC
型材
public partial class Profile
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Profile()
{
this.Posts = new HashSet<Post>();
}
public int Id { get; set; }
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Country_ { get; set; }
public System.DateTime DoB { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Post> Posts { get; set; }
}
}
帖子
public partial class Post
{
public int Id { get; set; }
public string Text { get; set; }
public System.DateTime DATE { get; set; }
public int ProfileId { get; set; }
public virtual Profile Profile { get; set; }
}
}
在我的ViewModel我有一個名爲的帖子列表PostList,我想用用戶製作的所有Post記錄填充。所以,我需要填充列表中的所有記錄,其中ProfileId中的職位等於配置文件的Id,這是由配置文件中的UserId是否等於當前用戶的身份確定。
總之,我需要:
郵冊=帖子,其中簡檔= Profiles.Id其中Profiles.UserId = CurrentUserId。
任何想法?我試過以下,但它是完全錯誤的:
var userId = User.Identity.GetUserId();
ViewModels.ProfileViewModel pVm = new ViewModels.ProfileViewModel();
pVm.PostList = db.Posts.Include(db.Profiles).Where(a => a.UserId == userId).ToList();
pVm.UserName = User.Identity.GetUserName();
return View(pVm);
請顯示您的個人資料和帖子模型 – Vecchiasignora
已更新爲來自實體模型的個人資料和帖子模型:) –
您沒有在做你說的應該做的事情,你正在比較Posts'UserId'到'userId'現在,但是在你的文本中你已經說過它應該比較帖子'ProfileId'到'userId'。因此它應該是'pVm.PostList = db.Posts.Include(db.Profiles).Where(a => a.ProfileId == userId).ToList();' – Luke