I am using Entity Framework Core in my project. My entity looks like this:
[Table("Policy")]
public class Policy
{
[Key]
public Guid Id { get; set; }
public Bank Bank { get; set; }
public string LastUpdateBy { get; set; }
}
[Table("Bank")]
public class Bank
{
[Key]
public Guid Id { get; set; }
public string Code { get; set; }
public DateTime? CreateTs { get; set; }
}
In SQL, this is how table Policy looks like:
Id (uniqueidentifier)
Bank (varchar)
LastUpdateBy (varchar)
I am referencing Bank in Policy entity because i would like to have a parent-child relationship.
When I am trying to add a record in Policy table, it's giving me following error
Violation of PRIMARY KEY constraint 'PK_Bank'. Cannot insert duplicate key in object 'dbo.Bank'. The duplicate key value is (829e0798-c7ee-4fcf-b18d-0fbc60f63fad).
Here is my code:
var policy = new Policy
{
Bank = new Bank
{
Id = "829e0798-c7ee-4fcf-b18d-0fbc60f63fad"
},
Id = Guid.NewGuid(),
LastUpdateBy = "User"
};
dbContext.Policy.Add(policy);
dbContext.SaveChanges();
I know, it's trying to add a record in Bank table as well. How would I tell EF Core to insert record only in Policy table?
GUIDinside of classPolicy, not aBankobject