我的数据库中有这样结构的表:
CREATE TABLE [dbo].[FDTransaction]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[FamilyId] [int] NULL,
[BankId] [int] NULL,
[Account_No] [numeric](25, 0) NULL,
[Amount] [int] NULL,
[Interest_Percent] [decimal](18, 0) NULL,
[Tenure] [int] NULL,
[MaturityDate] [datetime] NULL,
[InterestAmount] [int] NULL,
CONSTRAINT [PK_FDTransaction]
PRIMARY KEY CLUSTERED ([ID] ASC)
) ON [PRIMARY]
我有一个模型类,它代表代码中的数据库表:
public class FDTransaction
{
[Key]
public int ID { get; set; }
public int Familyid { get; set; }
public int BankId { get; set; }
public decimal Account_No { get; set; }
public int Amount { get; set; }
public double Interest_Percent { get; set; }
public int Tenure { get; set; }
public DateTime MaturityDate { get; set; }
public int interestAmount { get; set; }
}
当我在下面提到的行的表中添加记录时出现错误。
dbentities.Transactions.Add(transaction);
下面还有错误堆栈。
StackTrace:
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Invalid column name 'ID'.
Invalid column name 'ID'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=5
Number=207
如上所述,我在表中确实有列 ID
。我在 FDTransaction
类中也有属性 ID
。我仍然无法在数据库中添加行。
最佳答案
自 ID
列是 IDENTITY
列,您需要将另一个属性( [DatabaseGenerated]
)添加到您的 ID
模型类中的字段告诉 EF 这是一个 IDENTITY
列,它不需要提供值 - SQL Server 将在您插入行时设置值。
试试这个:
public class FDTransaction
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
.... (your other properties here, same as before) ......
}
关于c# - 无效的列名称 ID-Entity Framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49597823/