2013-05-16 127 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); 
    } 
相关问题