TelJanini
TelJanini

Reputation: 835

Entity Framework Reverse POCO Generator - Custom Navigation Property

I'm currently working with a legacy database that's missing a relationship between two tables.

Basically, I have a table of 'Items' and a table of 'Vendors' with their own respective primary keys.

However, the 'Items' table contains a field 'VendorNumber' that is used to map to the 'Vendors' table . This relationship is not enforced in the database, but I'd still like to use 'Vendors' as a navigation property from the 'Items'.

I'm using the 'Reverse POCO Generator', but I'm unable to figure out how to 'force' it to generate the navigation property.

I've tried making another 'ItemConfiguration' partial class that includes the property, but as it's set in the 'ItemConfiguration' constructor, I'm unable to achieve the desired functionality.

Any assistance/insight would be greatly appreciated!

Upvotes: 1

Views: 973

Answers (1)

TheSoftwareJedi
TheSoftwareJedi

Reputation: 35236

Create a partial class and add the relationship to the Vendor from Item

public partial class Item
{
    public virtual Vendor ItemVendor { get; set; } 
}

Create a partial class for the configuration and inplement the InitializePartial method that the generated partial class calls from the constructor

public partial class ItemConfiguration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<Item>
{
    partial void InitializePartial()
    {
        HasOptional(a => a.ItemVendor).WithMany().HasForeignKey(a => a.VendorNumber).WillCascadeOnDelete(false); 
    }
}

Your Item class will now have a ItemVendor field filled out.

Upvotes: 4

Related Questions