Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用一个实体将数据输入到一个极其简单的表中;名称“;_C#_Asp.net Mvc_Asp.net Mvc 4 - Fatal编程技术网

C# 如何使用一个实体将数据输入到一个极其简单的表中;名称“;

C# 如何使用一个实体将数据输入到一个极其简单的表中;名称“;,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我只想用以下结构将数据输入名为ProductTable的SQL表: CREATE TABLE [dbo].[ProductTable] ( [ID] INT NOT NULL, [Name] NVARCHAR (50) NOT NULL, CONSTRAINT [PK_ProductTable] PRIMARY KEY CLUSTERED ([ID] ASC) ); 我在model文件夹中有一个名为TableModel.cs的模型类 using

我只想用以下结构将数据输入名为
ProductTable
的SQL表:

CREATE TABLE [dbo].[ProductTable] (
    [ID]   INT           NOT NULL,
    [Name] NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_ProductTable] PRIMARY KEY CLUSTERED ([ID] ASC)
);
我在
model
文件夹中有一个名为
TableModel.cs
的模型类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;
using System.ComponentModel.DataAnnotations.Schema;

namespace Father.Models
{
        [Table("ProductTable")]
        public class ProductTable
        {
            public string Name { get; set; }
        }
}
和另一个名为
TableModelEntities.cs
的类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace Father.Models
{
    public class TableModelEntities : DbContext
    {
        public DbSet<ProductTable> Products { get; set; }
    }
}

但什么也没发生。你们能帮我吗?我想我错过了一件大事

您应该保存以提交更改:

dbproduct.SaveChanges()
:

SaveChanges将在此上下文中所做的所有更改保存到基础数据库


如果要将更改推送到数据库,则需要调用SaveChanges:

public ActionResult Table()
    {
        ProductTable product = new ProductTable();
        product.Name = "AAA";
        dbproducts.Products.Add(product);

        dbproducts.SaveChanges();

        return View(product);

    }
编辑:如果您的
ProductTable
类中没有反映您的ID列,我真的认为您的模型将无法工作。我会尝试添加ID列,看看是否有效

此外,请确保正确处理了数据库上下文。有关详细信息,请查看此博客帖子:

您可以确保控制器正在处理上下文,或者使用
using
语句为该更新创建一个上下文

using (TableModelEntities dbproducts = new TableModelEntities())
{
    //do stuff
}

当我展示TableData时,仍然没有任何变化,当这些变化将要发生时,实际上,当这个ActionResult发生时?对不起,我是mvc的新手,读过一些东西,但是提问对我来说有点容易me@spirit_seller您指向的是另一个数据库,而不是创建表的数据库。查看你的web.config,看看我应该在web.config中检查/写些什么才能让它工作@spirit\u卖家两个问题了解更多信息:你确认你的DB连接工作了吗?如果手动将数据放入并使用上下文检索数据,会发生什么情况?另外,您的ID列是自动增量列吗?@SimonC及其ASP.NET MVC 4 WEB应用程序,它从已创建的注册表/模型/控制器开始,因此我猜DB可以工作。对于ID列,表的代码在上面,因此ID列设置为set主键
using (TableModelEntities dbproducts = new TableModelEntities())
{
    //do stuff
}