DarioN1
DarioN1

Reputation: 2552

.net core 2.0 Entity Framework - Add table relationship at db level and update model

I'm working on an application who implements .net core 2.0 with Entity Framework.

I have generated the model by scaffolding the existent db using package manager console.

Now I have manually edited the database by adding a missing relationship between two tables.

What is the best way to update the model?

In this moment I'm deleting all the model files and I run the scaffolding command each time...

How to avoid this ?

Thanks to support

Upvotes: 0

Views: 332

Answers (1)

Natan
Natan

Reputation: 4968

You can simply add the missing virtual fields to the objects.

If the columns have matching names, you can simply add them directly:

class Customer {
    public int CustomerId {get;set;} // PK that was already there

    // new navigation property
    public virtual ICollection<Account> Accounts { get; set; }
}

class Account {
    public int AccountId {get;set;} 

    // new FK
    public int CustomerId { get;set; }
    // new navigation property
    public virtual Customer Customer {get;set;} 
}

In case you have multiple fks to the same table, or names don't match, you may have to add some code to the OnModelCreating method on your DbContext.

The simpler way to see how this is done is to regenerate once your code with your tool and compare the old one with a tool like WinMerge. EF Core is much simpler than EF6, once you understand the idea you'll never have to use these tools again. I hand code all my entities and I find it much easier than using these tools.

Upvotes: 1

Related Questions