如何在MVC中插入时处理标识列

时间:2014-09-01 06:06:26

标签: sql asp.net-mvc asp.net-mvc-4

我正在学习MVC&有一个演示MVC应用程序,我试图保存UserId,Name&电子邮件。

UserId是int主键&身份也是如此。

在我的创建视图页面中,我有Name&amp ;;的字段。仅限电子邮件但是在帖子上它也为UserId采用了int(0)的默认值,因此我得到了以下异常。

Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF.

这是我的Model类:

 namespace LearningMvc.Models
 {
 public class Users
 {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    [Required(ErrorMessage = "Please enter your name")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please enter your email address")]
    [RegularExpression(".+\\@.+\\..+",
    ErrorMessage = "Please enter a valid email address")]
    public string Email { get; set; }
}
}

这是我的行动方法:

    [HttpPost]
    public ActionResult Create([Bind(Exclude = "UserId")] Users NewUser)
    {
        try
        {
            var ObjDbContext = new MyDbDataContext();
            ObjDbContext.Users.InsertOnSubmit(NewUser);
            ObjDbContext.SubmitChanges();
            return RedirectToAction("Index");
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }

配置中的连接字符串

 <connectionStrings>
<add name="DemoDbForMvcConnectionString" connectionString="Data Source=RASHMITAD7;Initial Catalog=DemoDbForMvc;Integrated Security=True"
  providerName="System.Data.SqlClient" />

这是dbml文件:

       <?xml version="1.0" encoding="utf-8"?><Database Name="DemoDbForMvc" Class="MyDbDataContext" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">
    <Connection Mode="WebSettings" ConnectionString="Data Source=RASHMITAD7;Initial Catalog=DemoDbForMvc;Integrated Security=True" SettingsObjectName="System.Configuration.ConfigurationManager.ConnectionStrings" SettingsPropertyName="DemoDbForMvcConnectionString" Provider="System.Data.SqlClient" />
    <Table Name="dbo.[Users]" Member="Users">
      <Type Name="Users">
        <Column Name="UserId" Type="System.Int32" DbType="Int NOT NULL" IsPrimaryKey="true" CanBeNull="false"/>
        <Column Name="Name" Type="System.String" DbType="NVarChar(100)" CanBeNull="true" />
        <Column Name="Email" Type="System.String" DbType="NVarChar(50)" CanBeNull="true" />
      </Type>
    </Table>
  </Database>

1 个答案:

答案 0 :(得分:0)

我对dbml不是很熟悉,所以我会提出一个稍微不同的解决方案来帮助你入门。这基本上做的是保持你的模型不变,并使用类中的强类型数据来创建数据库:

的ConnectionString:

<add name="DemoDbForMvcConnectionString" connectionString="Data Source=RASHMITAD7;Initial Catalog=DemoDbForMvc;Integrated Security=True"
  providerName="System.Data.SqlClient" />

型号:

public class Users
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }

        [Required(ErrorMessage = "Please enter your name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter your email address")]
        [RegularExpression(".+\\@.+\\..+",
        ErrorMessage = "Please enter a valid email address")]
        public string Email { get; set; }
    }

数据背景:

public class DataContext: DbContext
    {
        public DbSet<Users> Users { get; set; }

        public DataContext() : base("DemoDbForMvcConnectionString") { }
    }

MVC行动:

[HttpPost]
public ActionResult Create([Bind(Exclude = "UserId")] Users user)
{
    var context = new DataContext();
    context.Users.Add(user);
    context.SaveChanges();

    return View();
}

您可以将dbml设置作为数据注释添加到模型中。