[英]Entity Framework LINQ Insert
I'm trying to use LINQ to insert an object in my database. 我正在尝试使用LINQ在数据库中插入一个对象。 My primary key is auto increment. 我的主键是自动递增。 Do I need to increment the id in my code or Entity Framework can do it? 我是否需要在代码中增加id或Entity Framework可以做到?
I have my dbContext: 我有dbContext:
TravelAgencyEntities db = new TravelAgencyEntities();
I'm trying to insert a User object: 我正在尝试插入User对象:
User newUser = new User();
newUser.FirstName = firstName.Text.ToString();
newUser.LastName = lastName.Text.ToString();
newUser.Email = email.Text.ToString();
newUser.Password = password.Text.ToString();
db.Users.Add(newUser);
db.SaveChanges();
It returns an exception: 它返回一个异常:
{"An error occurred while updating the entries. See the inner exception for details."}
I think that error is because I do not set the id in my object, but it should be auto increment. 我认为该错误是因为我没有在我的对象中设置id,但是它应该是自动递增的。 Does anyone know the problem? 有人知道这个问题吗?
The INNER ERROR: 内部错误:
Cannot insert explicit value for identity column in table 'User' when IDENTITY_INSERT is set to OFF
If you use code first, probably have set following code in DbContext OnModelCreating. 如果您首先使用代码,则可能已在DbContext OnModelCreating中设置了以下代码。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>()
.Property(a => a.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
Or set as attribute like following 或设置为以下属性
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
.....
}
you must change None to Identity. 您必须将无更改为身份。 Identity option is default for key. 身份选项是密钥的默认选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.