3

I'm working with MVC and have created a form to insert values into my database.

My database structure has the relationships:

  • One -> Many
  • Many -> Many

For Example: The User table contains a foreign key to the table Company. In my View, I have a dropdownlist which contains all the companies.

What I probably need is a working example of inserting data into tables with foreign keys. I have searched around and tried many solutions but cannot figure out how to make it work.

Here's my code:

Model:

 public class DefaultConnection : DbContext
    {
        public DefaultConnection()
            : base("DefaultConnection")
        {
        }

        public DbSet<User> users{ get; set; }
    }

    public class Company
    {
        public int Id { get; set; }
        public string Name{ get; set; }
    }
public class User
    {
        public int Id { get; set; }

        [ForeignKey("Company")]
        public int Id_Company { get; set; }
        public Company Company{ get; set; }
    }

ViewModel:

public class MyViewModel
    {
        public MyViewModel()
        {
            this.u= new User();
            this.cl = new Companylist();  <== another class which i have create a selectlist
        }

        public User u{ get; set; }
        public Companylist cl{get;set;}
}

View:

<ol>
   <li>
      @Html.LabelFor(m => m.cl.Ncompany)<br />
      @Html.DropDownListFor(o => o.cl.Ncompany, Model.cl.Ncompany, "-- Select --", new { @class = "abc" })
    </li>
    <li>
      @Html.LabelFor(m => m.u.Name)<br />
      <input type="text" name="Name" value="" />
    </li>
</ol>

Controller:

 [HttpPost]
        public ActionResult Create(MyViewModel model)
        {
            if (ModelState.IsValid)
            {
                db.users.Add(model);?????????????????
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(model);
        }
4

2 回答 2

7

首先,您的 DropDownListFor 似乎设置不正确,因为下拉列表是针对 User.Id_Company 而不是针对公司列表的。它很可能应该是:

<li>
      @Html.LabelFor(m => m.cl.Ncompany)<br />
      @Html.DropDownListFor(o => o.u.Id_Company, Model.cl.Ncompany, "-- Select --", new { @class = "abc" })
    </li>

接下来,在您的控制器中,您可以直接从返回的模型中插入,但在某些时候,您可能会退出使用域模型(数据库表的模型)并开始使用视图模型。话虽如此,您可以像这样添加一个新用户:

[HttpPost]
public ActionResult Create(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        var db = new DefaultConnection(); (?? is this what your context is called?)
        db.users.Add(new User{
           Id_Company = model.u.Id_Company, 
           Name = model.u.Name
        });
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(model);
}
于 2013-08-28T17:12:01.197 回答
1

ViewModel有一个CompanyUser。插入时需要将实体与数据库表实体进行匹配。

尝试这样做:

[HttpPost]
        public ActionResult Create(MyViewModel model)
        {
            if (ModelState.IsValid)
            {
                db.users.Add(model.User);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(model);
        }

使用外键插入表应该就像任何其他插入一样。假设您有一个公司的数据库行,它应该可以正常运行。

User user = new User
{
    Id_Company = 1
}

db.users.Add(user);
db.SaveChanges();
于 2013-08-28T16:47:02.477 回答