C# MVC - 将帖子数据插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18493683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:23:43  来源:igfitidea点击:

MVC - Insert post data into database

c#mysqlsqlasp.net-mvcentity-framework

提问by user2232273

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

我正在使用 MVC 并创建了一个表单来将值插入到我的数据库中。

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);
        }

采纳答案by Tommy

First, it appears that your DropDownListFor is not setup quite right in the sense that the drop down is for User.Id_Company and not for the company list. It most likely should be:

首先,从下拉列表用于 User.Id_Company 而不是公司列表的意义上说,您的 DropDownListFor 似乎设置得不太正确。最有可能的应该是:

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

Next, in your controller, you can insert directly from the model being returned, but at some point, you are probably going to quit using Domain Models (models of your DB tables) and start to use View Models. With that said, you could add a new user as such:

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

[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);
}

回答by Moe Bataineh

Your ViewModelhas a Companyand User. You need to match the entity with the database table entity when inserting.

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

Try doing this:

尝试这样做:

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

            return View(model);
        }

Inserting into a table with a foreign key should just be like any other insert. Assuming you have a database row for the company, it should run without a error.

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

User user = new User
{
    Id_Company = 1
}

db.users.Add(user);
db.SaveChanges();