I have a parent table as CustomerRequest that has a relationship with Loan table as 1 to 1-0, that means customer request can have 1 or 0 Loan in Loan Table. I have problem in getting a correct relationship in Entity Framework code first.
This is My CustomerRequest Table Script with correct relationship:
CREATE TABLE [Loan].[CustomerRequest]
(
[Id] INT IDENTITY(1,1)
,[CorrelationId] VARCHAR(500)
,[CustomerNumber] BIGINT
....
CONSTRAINT PK_CustomerRequest PRIMARY KEY([Id])
)
this is loan table:
CREATE TABLE [Loan].[Loan]
(
[Id] INT IDENTITY(1,1)
,[CustomerRequestId] INT
.....
CONSTRAINT PK_Loan PRIMARY KEY([Id])
,CONSTRAINT FK_Loan_CustomerRequestId FOREIGN KEY([CustomerRequestId]) REFERENCES [Loan].[CustomerRequest]([Id])
)
This is my Customer Request Model:
public class CustomerRequest
{
public int Id { get; set; }
public string CorrelationId { get; set; }
.....
public virtual Loan Loan { get; set; }
}
and Loan Model:
public class Loan
{
public int Id { get; set; }
public int CustomerRequestId { get; set; }
....
public virtual CustomerRequest CustomerRequest { get; set; }
}
I have this relationship in CustomerRequestMap:
HasKey(t => t.Id).HasOptional(t => t.Loan).WithRequired(t => t.CustomerRequest);
I get this error when I try to insert to Loan table:
{"Cannot insert explicit value for identity column in table 'Loan' when IDENTITY_INSERT is set to OFF."}