0
votes

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...

2

2 Answers

2
votes

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);
0
votes

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; }
}