简体   繁体   中英

How to specify foreign table key in EF Data Annotations?

I'm trying to configure relations between tables using Data Annotations of Entity Framework. I've found the following example :

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

     public int StdandardRefId { get; set; }

    [ForeignKey("StandardRefId")]
    public virtual Standard Standard { get; set; }
}

public class Standard
{
    public Standard()
    {
        StudentsList = new List<Student>();
    }
    public int StandardId { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

Now, the ForeignKey attribute informs, that StandardRefId is a foregin key. I guess, that EF deduces the target table from type of property ( Standard ). However, I fail to see, how to define, which column the foreign key refers to. I tried:

[Column("CompanyId")]
public int CompanyId { get; set; }

[ForeignKey("CompanyId")]
[InverseProperty("Id")]
public CompanyDAL Company { get; set; }

However, all I got was the following exception:

An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll

Additional information: The property 'Id' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type.

How can I explicitly say, that CompanyId points to Id property of Company table?

A Foreign Key will always refer to a Primary Key. When you create a navigation property to Company, that FK will refer to the PK of Company.

Entity Framework relies on every entity having a key value that it uses for tracking entities. One of the conventions that code first depends on is how it implies which property is the key in each of the code first classes. That convention is to look for a property named “Id” or one that combines the class name and “Id”, such as “BlogId”. The property will map to a primary key column in the database.

Source

What this means is that unless you have specified a different PK for Company, the "Id" property (and column) will be the PK for that entity.


Note: For the example you found, Standard uses the second convention for PK ie Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM