简体   繁体   中英

Map property based on a column that is not a Foreign Key in Entity Framework

I am trying to map the Country property using the CountryCode column, which is not the PK column in the Country table.

public class User
{

   [ForeignKey("Country")   
   public string CountryCode { get;set; }


   public virtual Country Country
}

public class Country 
{ 
   [Key]
   public int CountryId {get;set;}

   public string CountryCode {get;set;}

}

Currently the above doesn't work because CountryCode isn't a foreign key. How do I map this in EF 6 so that it loads the property based on the CountryCode and not look for the FK in the Country table.

Like This:-

public class User
{
  // other properties.

  public virtual Country Country;

}

public class Country 
{ 
   public int Id {get;set;}
   public string CountryCode {get;set;}
}

Entity Framework should be able to work out form here the relationship. It will create a Country_Id field in your DB. You could also create a Mapper class using the Fluent API.

a quick example :-

public class UserMap : EntityTypeConfiguration<User>
{

  public UserMap()
  {
     HasOptional(x=>x.Country);
  }

}

Dont Think you can via "Foreign key". EF will expect the key of the foreign table to be key. :-)

You could use validation trigger to check. You would need to code the check. if Your Poco implements : IValidatableObject then EF will call

public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {}

when updating your object.
You can code the association check there.

Given this looks like code first against a DB. If you wish to retain the public virtual Country Country; You will need to load the Property Country yourself . and Mark it as [NotMapped]

If this is an existing DB you are coding to , EF power tools have a reverse engineer code first from DB option. This tool can provide some valuable insight.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM