简体   繁体   English

实体框架,如果不指定主键就无法添加新对象

[英]Entity Framework, cannot add new object without specifying primary key

I am trying to use Identity to make the tables autoincrement the key upon insert. 我正在尝试使用身份使表在插入时自动递增键。 It worked nicely when I used a simple SQL query to insert a value. 当我使用简单的SQL查询插入值时,它的工作效果很好。

CREATE TABLE [dbo].[extrak] 
(
    [Id]                   INT         IDENTITY (1, 1) NOT NULL,
    [kategorianev]         VARCHAR(50) NULL,
    [nev]                  VARCHAR(50) NULL,
    [ar]                   INT         NULL,
    [szin]                 VARCHAR(50) NULL,
    [tobbszor_hasznalhato] TINYINT     NULL,

    PRIMARY KEY CLUSTERED ([Id] ASC)
);

However when I use C# code to add a value, I get an exception saying that I should set identity_insert on (I suppose this is when I want to specify a primary key, but I might have missed something). 但是,当我使用C#代码添加值时,出现一个异常,提示我应将set identity_insert on (我想这是我想指定主键的时候,但是我可能错过了一些东西)。 I tried setting It on also, but didn't work (right before calling the add method). 我也尝试将其设置为打开,但是没有用(在调用add方法之前)。

extrak extra = new extrak();
extra.kategorianev = categoryname;
extra.nev = name;
extra.ar = price;
extra.szin = color;
extra.tobbszor_hasznalhato = b;
Console.WriteLine("1");
DataBaseHandler.AddNewExtra(extra);
Console.WriteLine("2");
DataBaseHandler.SaveDB();

The exception happens on saving. 保存时会发生例外。 Do I have to find the new primary key for myself, and insert that way? 我是否必须为自己找到新的主键,然后以这种方式插入? Or can I make Entity Framework handle It somehow? 还是可以让Entity Framework以某种方式处理它?

My mate got It. 我的伴侣知道了。 I had to update the model in VS to make It work. 我必须在VS中更新模型以使其正常运行。

After that the code above worked nicely. 之后,上面的代码运行良好。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在实体框架中创建新记录而不在其参数中指定主键? - How to create a new record in Entity Framework without specifying the primary key in its parameters? 在没有主键的情况下将实体保存在实体框架中 - Save entity in Entity Framework without a primary key 实体框架6 / SQLite:无法按主键过滤 - Entity Framework 6 / SQLite: cannot filter by primary key 实体框架 - Oracle:没有主键的视图 - Entity Framework - Oracle : view without primary key 在实体框架中查找给定主键的对象 - Find object for given primary key in entity framework 实体框架 - 存储过程结果作为没有主键的实体 - Entity Framework - Stored Procedure result as an entity without Primary Key 实体框架代码优先-通过主键将子实体添加到父实体 - Entity Framework Code First - Add Child Entity to Parent by Primary Key 代码生成:向实体框架添加主键/外键 - Code Generation : Add primary key / foreign key to Entity Framework 使用迁移实体框架核心添加数据而无需指定ID - Add data using migration Entity Framework Core without specifying the id 实体框架数据库优先-不带主键的表 - Entity Framework database-first - table without primary key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM