简体   繁体   English

基于实体框架中非外键的列的地图属性

[英]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. 我正在尝试使用CountryCode列而不是Country表中的PK列来映射Country属性。

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. 目前,以上操作无效,因为CountryCode不是外键。 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. 如何在EF 6中对此进行映射,以使其基于CountryCode加载属性 ,而不在Country表中查找FK。

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. 它将在您的数据库中创建一个Country_Id字段。 You could also create a Mapper class using the Fluent API. 您也可以使用Fluent API创建Mapper类。

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. EF希望外表的键是键。 :-) :-)

You could use validation trigger to check. 您可以使用验证触发器进行检查。 You would need to code the check. 您需要对支票进行编码。 if Your Poco implements : IValidatableObject then EF will call 如果您的Poco实现: IValidatableObject则EF将调用

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; 如果您希望保留public virtual Country Country; You will need to load the Property Country yourself . 您将需要自己加载Property Country。 and Mark it as [NotMapped] 并将其标记为[NotMapped]

If this is an existing DB you are coding to , EF power tools have a reverse engineer code first from DB option. 如果这是您要编码的现有数据库,则EF电动工具首先具有来自数据库选项的反向工程师代码。 This tool can provide some valuable insight. 该工具可以提供一些有价值的见解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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