问题描述
在设置数据库(SQL Server)的主键标识
在使用EF中插入数据,我得到错误
with this particular entity, though I am using the same approach with other entities to insert the data and getting no error with them.
public class MyTable
{
[Key/*,DatabaseGenerated(DatabaseGeneratedOption.Identity)*/]
public int ID{get;set;}
public string name {get;set;}
public string type {get;set;}
public string status {get;set;}
public int country {get;set;}
public DateTime start_date {get;set;}
public DateTime due_date {get;set;}
}`
Query
MyTable check= new MyTable();
check.name = checkName;
check.type = "DB";
check.status = "New";
check.country = country;
check.start_date = DateTime.Now;
check.due_date = dueDate;
db.myTables.Add(check);
db.SaveChanges();
Updated :
After uncommenting the above line
(DatabaseGenerated(DatabaseGeneratedOption.Identity))
it's throwing an exception
I am not sure if it is in your case too....but the second error says..you are using your primary key as foreign key in some relation which is only valid for property having DatabaseGeneratedOption.None .
So to use your primary key as identity you can decorate it with DatabaseGeneratedOption.Identity
and in that case it will throw an exception because you can not use identity for relation(use DatabaseGeneratedOption.None instead).
这篇关于EF code第一:无法插入表'mytable的“标识列显式值时IDENTITY_INSERT设置为OFF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!