使用组合密钥(主要)将数据从EF插入到DB中 [英] Insert data into DB from EF using composite key (primary)

查看:116
本文介绍了使用组合密钥(主要)将数据从EF插入到DB中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据未插入数据库,如何处理复合主键,其中一个PK设置为自动递增。这里没有在Id列中输入任何数据,但它抛出异常。



Data is not inserting into DB, How handle composite primary key, where one PK is set to auto-increment. Here not entering any data into Id column , but it throws following exception .

"Cannot insert explicit value for identity column in table 'TableName' when IDENTITY_INSERT is set to OFF."





我尝试过:





What I have tried:

Table 
Id int primary key (auto increment)
SrNo varchar(6) primary key
Name varchar(10)

<pre lang="c#">   this.HasKey(m => new { m.Id, m.SrNo });




public bool Add(BusinessEntity mod)
                   {  _itemWarehouse.Insert(mod);   }





从WinForm获取数据

Id = 0(未设置,默认值),SrNo = X12,名称= ABC



但是没有将数据输入DB,抛出异常



无法插入当IDENTITY_INSERT设置为OFF时,表'TableName'中的标识列的显式值。



taking data from WinForm where
Id=0 (didn't set, default), SrNo = X12 , Name = ABC

But not entering data into DB , throwing exception

"Cannot insert explicit value for identity column in table 'TableName' when IDENTITY_INSERT is set to OFF."

推荐答案

一个表不能有多个主键。



EF只能识别一个主键;单个值或复合键。



其他任何东西都是二级密钥/索引
A table cannot have more than one "primary key".

EF can only recognize one primary key; either a single value or a compound key.

Anything else would be a "secondary key / index"


这篇关于使用组合密钥(主要)将数据从EF插入到DB中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆