Sam
Sam

Reputation: 1535

EF Navigation Property in Database first

I have a database and I want to know how to map the relationships via code. I'm not sure if I understand exactly how this works.

Suppose I have two classes:

public class Address
{
    [Key]
    public int AddressID {get;set;}
    public String Street {get;set;}
}

public class Shipment
{
    [Key]
    public int ShipmentID {get;set;}
    public int ShipToAddressID {get;set;}

    public virtual Address ShipToAddress {get;set;}
}

I have a few questions: Does the navigation property merely give me access to the dbset of Address? It seems that is not the case. However, if not, how do I specify which property is the foreign key on which the relationship exists? eg: How do I tell this navigation property that it should match the Address entities based on the AddressID property ?

Again, I'm doing this all via code. So I'm mapping the properties in the OnModelCreating call in the context. So please make suggestions/provide answers with that in mind.

Upvotes: 1

Views: 3108

Answers (1)

LSU.Net
LSU.Net

Reputation: 849

You are in need of the HasRequired, WithMany, and HasForeignKey configuration methods.

EntityTypeConfiguration<Shipment> config = modelBuilder.Entity<Shipment>();

config
   .HasRequired(s=>s.ShipToAddress)
   .WithMany()
   .HasForeignKey(s=>s.ShipToAddressID)
   .WillCascadeOnDelete(false);

Upvotes: 1

Related Questions