User
,每当我尝试将其添加到数据库时,ID
0
为create table Users
(
ID bigint not null primary key,
FirstName nvarchar(50) not null,
LastName nvarchar(50) not null,
BirthDate smalldatetime not null,
Email varchar(50) not null,
UserName nvarchar(50) not null,
Password nvarchar(50) not null
)
。据我所知,每次添加内容时,SQL都会自动生成Id,但它并没有发生。我做错了什么?
SQL
public class User
{
//public long ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public User AddNewUser(Register signedUser)
{
using (MyDBEntities context = new MyDBEntities())
{
User newRegisteredUser = new User {FirstName = signedUser.FirstName, LastName = signedUser.LastName, BirthDate = signedUser.BirthDate, Email = signedUser.Email, UserName = signedUser.UserName, Password = signedUser.Password };
context.Users.Add(newRegisteredUser);
context.SaveChanges();
return newUser;
}
}
C#
{{1}}
答案 0 :(得分:4)
您需要将其声明为IDENTITY列,如下所示:
create table Users (
ID bigint IDENTITY(1,1) not null primary key,
FirstName nvarchar(50) not null,
LastName nvarchar(50) not null,
BirthDate smalldatetime not null,
Email varchar(50) not null,
UserName nvarchar(50) not null,
Password nvarchar(50) not null
)
答案 1 :(得分:2)
您需要执行以下操作:
ID
标记为IDENTITY,这将确保Sql Server将设置每条记录中列的值。DatabaseGeneratedOption.Identity
标记属性,以便不会使用Insert将值发送到数据库并且在插入完成后,将回读Sql Server添加的值并将其应用于模型。您可以使用任何属性或流利的表示法来执行此操作。脚本:
CREATE TABLE Users (
ID bigint IDENTITY(1,1) NOT NULL PRIMARY KEY,
FirstName nvarchar(50) not null,
LastName nvarchar(50) not null,
BirthDate smalldatetime not null,
Email varchar(50) not null,
UserName nvarchar(50) not null,
Password nvarchar(50) not null
)
EF模型:
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
int
用于您的Id列,除非您正在设计一个全世界人口都将使用的系统。*