Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework mapping when foreign key column name is different

I have a legacy table like this:

Country
- countryCode (PK, varchar(10), not null)

Now I have a new table:

Store
- store_id
- country_code

My models:

public class Country
{
   [Key]
   [Column("countryCode")
   public int CountryCode {get;set;}
}


public class Store
{
   [Key]
   [Column("store_id")
   public int Id {get;set;}

   [Column("country_code")]
   public int CountryCode {get;set;}
}

Now I want to be able to do this:

var store = // get store

store.Country.CountryCode

How can I create this mapping? Notice that the column names are not the same (I can't change this).

I believe I have to add this to my Store model, but how do I specificy the foreign key's seeing as they have different names?

public virtual CountryCode {get;set;}
like image 756
loyalflow Avatar asked Mar 25 '26 09:03

loyalflow


1 Answers

If your database column has a type of varchar(10) you cannot use an int property in your model but you must use a string, no matter if the property name matches the column name or not. Also in order to be able to access the Country from the Store you need a navigation property Store.Country:

public class Country
{
    [Key]
    [Column("countryCode", TypeName = "varchar")]
    [MaxLength(10)]
    public string CountryCode { get; set; }
}

public class Store
{
    [Key]
    [Column("store_id")
    public int Id { get; set; }

    [Column("country_code", TypeName = "varchar")]
    [MaxLength(10)]
    [Required]
    [ForeignKey("Country")]
    public string CountryCode { get; set; }

    public virtual Country Country { get; set; }
}

(It's possible that the ForeignKey attribute is not necessary. You can try it without it. Also remove the [Required] attribute if the country_code column in table Store allows NULL values.)

You should be able now to access the CountryCode with for example:

var store = context.Stores.Find(1);
string countryCode = store.Country.CountryCode;

The store.Country navigation property will be loaded automatically via lazy loading (hence the virtual modifier) when you access the property.

like image 114
Slauma Avatar answered Mar 27 '26 21:03

Slauma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!