And*_*mar 11 c# sql-server entity-framework ef-code-first
为了将此问题简化为简单版本,我创建了此表:
create table TestTable(id int primary key, descr varchar(50))
Run Code Online (Sandbox Code Playgroud)
请注意,该id
字段不是标识字段.现在,如果我尝试使用EF Code First插入一行:
[Table("TestTable")]
public class TestTable
{
[Key]
public int id { get; set; }
public string descr { get; set; }
}
public class TestContext : DbContext
{
public TestContext(string connectionString) : base(connectionString) {}
public DbSet<TestTable> TestTables { get; set; }
}
static void Main()
{
const string connectionString = "...";
using (var db = new TestContext(connectionString))
{
db.TestTables.Add(new TestTable { id = 42, descr = "hallo" });
db.SaveChanges();
}
}
Run Code Online (Sandbox Code Playgroud)
结果是一个例外:
无法将值NULL插入列'id',表'TestTable'; 列不允许空值.
但是插入行的代码指定id = 42
.任何线索或暗示欢迎.
Gui*_* R. 19
只需添加此DataAnnotations [DatabaseGenerated(DatabaseGeneratedOption.None)]
和库
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("TestTable")]
public class TestTable
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int id { get; set; }
public string descr { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2677 次 |
最近记录: |