Z.V
Z.V

Reputation: 1471

Entity Framework Custom Navigational Properties

Is there a way to map below ClassA.BId to ClassB.BetaId ? BetaId in ClassB is not primary key. Thus, mapping in following way end up in "The ForeignKeyAttribute is not valid" exception. Note that there is no foreign key relationship in these 2 classes. For some reason I must not map ClassA.BId to ClassB.Id because these 2 field is unrelated but I need to custom map ClassA.BId to ClassB.BetaId due to these 2 field is related. However, The Id in ClassB must remain as primary key.

Note: I'm using Entity Framework 6

[Table("A")]
public class ClassA{
    [Key]
    public int Id { get; set; }


    public int BId { get; set; }

    [ForeignKey("BId")]
    public virtual B B { get; set; }
}

[Table("B")]
public class ClassB{
    [Key]
    public int Id { get; set; }

    public int BetaId { get; set; }
}

Upvotes: 0

Views: 43

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89371

If B.BetaID is unique you can declare it to be the Key. Otherwise EF Core supports Foreign Key properties referencing Alternate Keys. See https://learn.microsoft.com/en-us/ef/core/modeling/alternate-keys

Upvotes: 1

Related Questions