2011-12-17 124 views
1

我拥有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 
} 

在我的创建方法控制我有这样的事情:

[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; } 
} 

但也没有工作。我究竟做错了什么 ?我会非常感谢任何帮助

谢谢。

+0

你可以显示`Post`类代码吗? – Eranga 2011-12-17 01:17:22

+0

查看更新后的帖子。谢谢Eranga – Ciwan 2011-12-17 01:39:21

回答

1

问题是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*/); 
相关问题