2011-12-17 123 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*/); 
相關問題