Ducati007
Ducati007

Reputation: 275

Mapping Foreign Key in EF5.0

I have the below tables as my entities

public class Customer
{
  public int CustId{get;set;}
  public string Name {get;set;}
}


public class Address
{
  public int Id{get;set;}
  public string Name {get;set;}
   **public virtual Customer Customer {get;set;}**
}

In my model configuration for Address using Fluent API. I have the below code

HasKey(p => p.Id);
HasRequired(p => p.Customer).WithMany().Map(m => m.MapKey("CustId"));

What I really want is instead of using public virtual Customer Customer {get;set;} I want to have Public Int CustID; property in Address Class... and still do the mapping
as foreign key.

Could someone please throw some suggestions...

Upvotes: 0

Views: 3214

Answers (2)

Chris Searles
Chris Searles

Reputation: 2422

Alternatively, you can use DataAnnotations:

public class Address
{
    [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public int CustId { get; set; }
    [ForeignKey("CustId")]
    public Customer Customer { get; set; }
}

Upvotes: 0

Mark Oreta
Mark Oreta

Reputation: 10416

You just need to add the property to your Address class:

public class Address
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CustId { get; set; }

    public virtual Customer Customer { get; set; }
}

and then update your fluent, instead of using the .map function use the .HasForeignKey function:

        modelBuilder.Entity<Address>()
            .HasRequired(p => p.Customer)
            .WithMany()
            .HasForeignKey(p => p.CustId);

Upvotes: 2

Related Questions