Entity Framework 6.1.3 外键映射到非主键
Entity Framework 6.1.3 Mapping Foreign key to non primary key
目标是 API 包含来自 GravityZone 的所有字段以及来自区域 table 的区域名称。我已经尝试了以下代码的几种排列但没有成功。它目前为区域提出了 null,我希望将名称作为字符串或对象的一部分。我正在使用无法修改的现有 table。
型号:
public partial class Zone
{
[Key]
[Column("ZONE_ID")]
public decimal ZoneId { get; set; }
[Column("ZONE_CODE")]
public decimal ZoneCode { get; set; }
[Column("ZONE_NAME")]
public string ZoneName { get; set; }
public virtual ICollection<GravityZone> GravityZones { get; set; }
}
public partial class GravityZone
{
[Key]
[Column("GRAVITY_ID")]
public decimal GravityZoneId { get; set; }
[Column("ZONE_CODE")]
public decimal ZoneCode { get; set; }
[Column("ELEVATION")]
public decimal Elevation { get; set; }
[Column("REMARK")]
[StringLength(2000)]
public string Remark { get; set; }
public virtual Zone Zone { get; set; }
}
上下文(仅关系部分)
modelBuilder.Entity<Zone>()
.HasKey(e => e.ZoneCode);
modelBuilder.Entity<GravityZone>()
.HasRequired(e => e.Zones);
除此部分外,其他一切都很好:
"Zones":null,
我不认为这是可能的,因为它会引起很多麻烦。外键应始终指向 table 的某个键。我认为您无法告诉 EF 关于候选键的信息。
编辑:
类似问题:Entity Framework 5.0 composite foreign key to non primary key - is it possible?
您的问题已得到解答。因为我认为 EF 不理解唯一性的概念,主键除外。
Entity Framework foreign keys to non-primary key fields
现在可以在 Entity Framework 7(即 EF Core 1.0)中实现。
来自 .Net Entity Framework 用户声音 Unique Constraint (i.e. Candidate Key) Support:
Support for this feature was added in EF Core 1.0 and we don’t have plans to add it in the EF6 codebase.
目标是 API 包含来自 GravityZone 的所有字段以及来自区域 table 的区域名称。我已经尝试了以下代码的几种排列但没有成功。它目前为区域提出了 null,我希望将名称作为字符串或对象的一部分。我正在使用无法修改的现有 table。
型号:
public partial class Zone
{
[Key]
[Column("ZONE_ID")]
public decimal ZoneId { get; set; }
[Column("ZONE_CODE")]
public decimal ZoneCode { get; set; }
[Column("ZONE_NAME")]
public string ZoneName { get; set; }
public virtual ICollection<GravityZone> GravityZones { get; set; }
}
public partial class GravityZone
{
[Key]
[Column("GRAVITY_ID")]
public decimal GravityZoneId { get; set; }
[Column("ZONE_CODE")]
public decimal ZoneCode { get; set; }
[Column("ELEVATION")]
public decimal Elevation { get; set; }
[Column("REMARK")]
[StringLength(2000)]
public string Remark { get; set; }
public virtual Zone Zone { get; set; }
}
上下文(仅关系部分)
modelBuilder.Entity<Zone>()
.HasKey(e => e.ZoneCode);
modelBuilder.Entity<GravityZone>()
.HasRequired(e => e.Zones);
除此部分外,其他一切都很好:
"Zones":null,
我不认为这是可能的,因为它会引起很多麻烦。外键应始终指向 table 的某个键。我认为您无法告诉 EF 关于候选键的信息。
编辑:
类似问题:Entity Framework 5.0 composite foreign key to non primary key - is it possible?
您的问题已得到解答。因为我认为 EF 不理解唯一性的概念,主键除外。
Entity Framework foreign keys to non-primary key fields
现在可以在 Entity Framework 7(即 EF Core 1.0)中实现。
来自 .Net Entity Framework 用户声音 Unique Constraint (i.e. Candidate Key) Support:
Support for this feature was added in EF Core 1.0 and we don’t have plans to add it in the EF6 codebase.