![](/img/trans.png)
[英]Can Entity Framework map the same column to a Navigation Property and a Foreign Key
[英]Map property based on a column that is not a Foreign Key in Entity Framework
我正在尝试使用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;}
}
目前,以上操作无效,因为CountryCode不是外键。 如何在EF 6中对此进行映射,以使其基于CountryCode加载属性 ,而不在Country表中查找FK。
像这样:-
public class User
{
// other properties.
public virtual Country Country;
}
public class Country
{
public int Id {get;set;}
public string CountryCode {get;set;}
}
实体框架应该能够在这里建立表格之间的关系。 它将在您的数据库中创建一个Country_Id字段。 您也可以使用Fluent API创建Mapper类。
一个简单的例子:
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
HasOptional(x=>x.Country);
}
}
不要以为您可以通过“外键”。 EF希望外表的键是键。 :-)
您可以使用验证触发器进行检查。 您需要对支票进行编码。 如果您的Poco实现: IValidatableObject
则EF将调用
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {}
更新对象时。
您可以在此处编码关联检查。
鉴于此,代码首先针对数据库。 如果您希望保留public virtual Country Country;
您将需要自己加载Property Country。 并将其标记为[NotMapped]
如果这是您要编码的现有数据库,则EF电动工具首先具有来自数据库选项的反向工程师代码。 该工具可以提供一些有价值的见解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.