mrjamiebowman
mrjamiebowman

Reputation: 115

Entity Framework Code First Foreign Key different column key

So, Addresses has a PK of Id and a foreign key of EntityKey which references the Vendors table's Id, because Vendors have Addresses for their physical buildings.

When I query Vendors, I'm not able to return an associated Address.

Note: I don't want to change the schema.

[Table("EE.Address")]
public partial class Address {
    [Key]
    public Guid Id { get; set; }

    [StringLength(50)]
    public string Address1 { get; set; }

    [StringLength(50)]
    public string Address2 { get; set; }

    [StringLength(50)]
    public string City { get; set; }

    [StringLength(5)]
    public string State { get; set; }

    [StringLength(30)]
    public string PostalCode { get; set; }

    [StringLength(10)]
    public string CountryCode { get; set; }

    public Guid EntityKey { get; set; }

    [ForeignKey("EntityKey")] 
    public virtual Vendor Vendor { get; set; }
    // EntityKey should be Vendor.Id
}


[Table("EE.Vendor")]
public partial class Vendor {
    [Key]
    public Guid Id { get; set; }

    [StringLength(50)]
    public string Name { get; set; }

    [StringLength(50)]
    public string AlternativeName { get; set; }

    [StringLength(50)]
    public string VendorCode { get; set; }

    [StringLength(50)]
    public string TaxId { get; set; }

    public Guid VendorTypeKey { get; set; }

    public Guid? ParentKey { get; set; }

    [ForeignKey("Id")]
    public virtual Address Address { get; set; }
}

Upvotes: 0

Views: 46

Answers (1)

Johnie Karr
Johnie Karr

Reputation: 2822

Try this:

[Table("EE.Address")]
public partial class Address {
    [Key]
    public Guid Id { get; set; }

    [StringLength(50)]
    public string Address1 { get; set; }

    [StringLength(50)]
    public string Address2 { get; set; }

    [StringLength(50)]
    public string City { get; set; }

    [StringLength(5)]
    public string State { get; set; }

    [StringLength(30)]
    public string PostalCode { get; set; }

    [StringLength(10)]
    public string CountryCode { get; set; }

    [ForeignKey("Vendor")]
    public Guid EntityKey { get; set; }

    public virtual Vendor Vendor { get; set; }
    // EntityKey should be Vendor.Id
}


[Table("EE.Vendor")]
public partial class Vendor {
    [Key]
    public Guid Id { get; set; }

    [StringLength(50)]
    public string Name { get; set; }

    [StringLength(50)]
    public string AlternativeName { get; set; }

    [StringLength(50)]
    public string VendorCode { get; set; }

    [StringLength(50)]
    public string TaxId { get; set; }

    public Guid VendorTypeKey { get; set; }

    public Guid? ParentKey { get; set; }

    [ForeignKey("Address")]
    public Guid AddressId {get; set; }

    public virtual Address Address { get; set; }
}

Upvotes: 1

Related Questions