【问题标题】:Code first database creation代码优先数据库创建
【发布时间】:2013-05-16 18:26:07
【问题描述】:

我有两个实体。用户和用户联系人。

我创建了两个类。 用户

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。

使用的Fluent api是。

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

【问题讨论】:

  • 您能否更具体地说明问题所在?插入中缺少您的主键?
  • 是的,当我插入时。它插入用户联系人,但用户 ID 变为空。
  • 显示插入数据的代码。
  • 写了一个答案,但我不认为你的“是”实际上是“是”。发布将项目添加到数据库的代码。
  • 您是否检查了PUsers 表中的UserContact_Id 字段?

标签: c# asp.net-mvc entity-framework code-first


【解决方案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);
    }

【讨论】:

    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    相关资源
    最近更新 更多