我具有ViewModel中两个实体的属性。这两个实体都相互关联,例如,用户和帖子。每个用户可以有多个帖子,并且多个帖子可以属于一个用户(一对多)。
我的ViewModel的目的是允许在同一表单上添加用户和帖子。所以我的ViewModel看起来像这样:
public class CreateVM
{
[Required, MaxLength(50)]
public string Username { get; set; }
[Required, MaxLength(500), MinLength(50)]
public string PostBody { get; set; }
// etc with some other related properties
}
在我的控制器上的Create方法上,我有类似这样的内容:
[HttpPost]
public ActionResult Create(CreateVM vm)
{
if (ModelState.IsValid)
{
User u = new User()
{
Username = vm.Username,
// etc populate properties
};
Post p = new Post()
{
Body = vm.PostBody,
// etc populating properties
};
p.User = u; // Assigning the new user to the post.
XContext.Posts.Add(p);
XContext.SaveChanges();
}
}
当我通过调试器遍历它时,一切看起来都很好,但是当我尝试查看该帖子时,它的用户关系为空!
我也尝试过
u.Posts.Add(p);
UPDATE:
我的Post类代码如下:
public class Post
{
[Key]
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
public User User { get; set; }
}
但是那也不起作用。我在做什么错?
问题是EF无法延迟加载User
属性,因为您尚未将其设为virtual
。
public class Post
{
[Key]
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
public virtual User User { get; set; }
}
如果您事先知道要访问该帖子的User
属性,则应该急于加载与该帖子相关的User
。
context.Posts.Include("User").Where(/* condition*/);