EF Core 2.1 is updating ID when I am simply Loading and Saving

99 Views Asked by At

EF Core 2.1 is updating ID when I am simply Loading and Saving values in Database.

Note: I am using Database first approach.

Error : Cannot update identity column 'ID'.

 string passportNumber = string.Empty;
    using (ApplicationDbContext db = new ApplicationDbContext(connectionString))
        {
            using (IDbContextTransaction transaction = db.Database.BeginTransaction())
            {
                try
                {
                    TLifting Lifting = new TLifting();
                    if (!string.IsNullOrEmpty(PassportNumber))
                    {
                        Lifting = db.TLifting.FirstOrDefault();
                    }
                    Lifting.Col1 = "TEST"

                    if (Lifting.PassportId == 0)
                    {
                        db.TLifting.Add(Lifting);
                    }
                    else
                    {
                        db.Entry(Lifting).State = EntityState.Modified;
                    }
                  
                    db.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    
                }
            }
        }

Entity

 CREATE TABLE [dbo].[T_Lifting](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [PassportID] [int] NOT NULL,
        [PassportTypeID]  AS ((5)) PERSISTED NOT NULL,
 CONSTRAINT [PK_T_Lifting_1] PRIMARY KEY CLUSTERED 
(
    [PassportID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [IX_T_Lifting] UNIQUE NONCLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[T_Lifting]  WITH CHECK ADD  CONSTRAINT [FK__T_Lifting__T_Passport] FOREIGN KEY([PassportID], [PassportTypeID])
REFERENCES [dbo].[T_Passport] ([PassportID], [PassportTypeID])
GO

ALTER TABLE [dbo].[T_Lifting] CHECK CONSTRAINT [FK__T_Lifting__T_Passport]
GO

Passport and Piping table are having one one relationship and ID column Identity column.

1

There are 1 best solutions below

6
Salahuddin Ahmed On

May be following settings would help you:

In protected override void onModelCreating(ModelBuilder modelBuilder) {} method, write the below line of code accordingly.

 modelBuilder.Entity<Type>().Property(u => u.ID).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);

Note: Here Type will be class model/object of yours.