2013-05-16 130 views
0

我有兩個實體。用戶和用戶聯繫人。代碼第一次創建數據庫

我創建了兩個類。 用戶

public class PUser 
{ 
    public int PUserId { get; set; } 

    public virtual UserContact UserContact { get; set; } 
} 

public class UserContact 
{ 
    public int UserContactId { get; set; } 

    public virtual PUser PUser { get; set; } 
} 

我可以有多個用戶的聯繫人,但在我的MVC觀點 - 我要添加只有一個用戶接觸。

我該怎麼做?以上是創建表格,但不在用戶聯繫表中插入Puserid。

流利的API使用的是。

modelBuilder.Entity<PUser>() 
       .HasOptional(p => p.UserContact).WithRequired(p => p.PUser); 
+0

你能更具體地說明問題是什麼嗎?您的主鍵在插入時是否丟失? –

+0

是的,當我插入。它插入用戶聯繫人,但userid變爲空。 –

+0

顯示插入數據的代碼。 –

回答

1

這是一個one-to-one關係,所以你需要在創建User初始化你UserContact。我就是這麼做的。

[HttpGet] 
    public ActionResult Create() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Create(PUser model)//You should use a ViewModel here 
    { 
     if (ModelState.IsValid) 
     { 
      var db = new EfDb(); // If you introduce abstration to you Context, you could avoid this.    
      var user= new PUser 
          { 
           Name = model.Name,            
           UserContact= new UserContact 
                { 
                 Phone = model.UserContact.Phone    
                } 
           }; 

      db.PUser.Add(user); 
      db.SaveChanges(); 
      return RedirectToAction("Index", "Home"); 
     }       
     return View(model); 
    } 
相關問題