Reputation: 4420
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."}
Upvotes: 0
Views: 437
Reputation: 157
You have to modify your entities and configurations a bit like this.
public class CustomerRequest
{
public int Id { get; set; }
public string CorrelationId { get; set; }
public virtual Loan Loan { get; set; }
}
public class CustomerRequestMap : EntityTypeConfiguration<CustomerRequest>
{
public CustomerRequestMap()
{
Property(x => x.Id)
.IsRequired()
.HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
}
}
public class Loan
{
//public int Id { get; set; }
[Key, ForeignKey("CustomerRequest")]
public int CustomerRequestId { get; set; }
public virtual CustomerRequest CustomerRequest { get; set; }
}
public class LoanMap : EntityTypeConfiguration<Loan>
{
public LoanMap()
{
HasRequired(m => m.CustomerRequest)
.WithOptional(m => m.Loan)
;
}
}
With this configuration you can have 1 - 0 or 1 relation but you have to modify your schema script.
You can't have Id
as primary key and CustomerRequestId
as foreign key, EF does not allow this in 1-0 or 1 relation. And it's a wrong design from schema point of view too.
Imagine the situation when you have CustomerRequest
with Id=1
. Then you insert two Loan
entry with CustomerRequestId=1
but with different Id
primary key. How will you query the two Loan
entry from EF model in 1-0 or 1 relation?
If the schema is fix and you can't modify it then you must go with 1-many relation.
Upvotes: 1