目标是拥有一个API,其中包含来自GravityZone的所有字段以及来自Zone表的区域名称。我已经尝试了以下代码的几种排列而没有成功。它目前为区域提供null,我希望将该名称作为字符串或对象的一部分。我正在使用我无法修改的现有表格。
型号:
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,
答案 0 :(得分:12)
现在可以在Entity Framework 7(即EF Core 1.0)中使用。
来自.Net实体框架用户语音 Unique Constraint (i.e. Candidate Key) Support :
EF Core 1.0中添加了对此功能的支持,我们没有计划将其添加到EF6代码库中。
答案 1 :(得分:-1)
I don't think it is possible cause it would cause a lot of trouble. Foreign key should should always point to some key of a table. I don't think you are able to tell EF about candidate keys.
Edit:
Similar Questions: Entity Framework 5.0 composite foreign key to non primary key - is it possible?
Here is answer for your question. As I thought EF does not understand the concept of uniqueness with exception of primary key.