Shaggy
Shaggy

Reputation: 5790

Entity Framework Core insert record into database

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?

Upvotes: 1

Views: 3711

Answers (2)

Pawel Gerr
Pawel Gerr

Reputation: 101

If you don't want to introduce a foreign key for Bank then you have to attach bank first.

var bank = new Bank
{
    Id = "829e0798-c7ee-4fcf-b18d-0fbc60f63fad"
};
dbContext.Bank.Attach(bank);

var policy = new Policy
{
    Bank = bank,
    Id = Guid.NewGuid(),
    LastUpdateBy = "User"
};

dbContext.Policy.Add(policy);
dbContext.SaveChanges();

Upvotes: 2

Ryan Wilson
Ryan Wilson

Reputation: 10765

A bank is an entity that exists as stated a (singleton), a bank will not change and it's properties are it's own. A policy is issued by a bank, therefore, a policy should reference a bank via the banks Guid or ID property (foreign key), this will then create the parent -> child relationship which you desire. This is a ONE-TO-MANY relationship. I think you may want to either spend some more time learning about database relational design or draw these things out on paper before creating your entity classes.

EDIT: Igor has given you an option to stay the course and not change your entities, but I think you should take a good hard look at structuring your entities in a way that would mirror a database relational design. Just my opinion.

Upvotes: 2

Related Questions