Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

c# - Entity Framework 6.1.3 Mapping Foreign key to non primary key

The goal is to have an API with all the fields from the GravityZone with the name of the zone coming from the Zone table. I've tried several permutations of the following code without success. It's currently coming up with null for the Zone which I'm hoping to get either the name as a string or part of the object. I'm working with existing tables that I'm not able to modify.

Models:

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; }
}

Context (only the relational portion)

modelBuilder.Entity<Zone>()
    .HasKey(e => e.ZoneCode);

modelBuilder.Entity<GravityZone>()
    .HasRequired(e => e.Zones);

Everything else comes back great except for this part:

"Zones":null,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is now possible in Entity Framework 7 (that is, EF Core 1.0).

From .Net Entity Framework User Voice 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...