[英]Invalid Column name ID-Entity Framework
我的數據庫中的表具有以下結構:
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
列,因此您需要在模型類的ID
字段中添加另一個屬性( [DatabaseGenerated]
),以告訴EF這是IDENTITY
列,並且不需要提供值-SQL Server插入行時將設置值。
嘗試這個:
public class FDTransaction
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
.... (your other properties here, same as before) ......
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.