Why do we need to declare a property in order to put Foreign Key attribute with the same name?

c# entity-framework entity-framework-6

Question

Why do we need to create a primitive type i.e. User_ID if I have to declare a foregin key name over reference navigational proeperty?

e.g.

    public class Sims
    {
        public int ID { get; set; }

        public int Users_ID { get; set; }
        [ForeignKey("Users_ID")]
        public Users Users { get; set; }
    }

Why do I need public int Users_ID { get; set; } in order to put only a foreign key attribute over the Users?

1
0
1/16/2019 10:57:24 AM

Accepted Answer

Because that's telling EF that the foreign key field to use to store the id of the linked "Users" record is named "Users_ID".
If you don't explicitly need to have that field available in your Sims Entity, then you can just leave it out altogether & you don't need to have the ForeignKey Attribute at all & EF will manage that for you behind the scenes.

Alternatively, you could name the foreign key field "UsersId" and it will assume that's the foreign key due to convention.

So any of these should be completely fine:

//no explicit foreign key
public class Sims
{
    public int ID { get; set; }
    public Users Users { get; set; }
}

//explicit foreign key but EF works it out via convention
public class Sims
{
    public int ID { get; set; }
    public int UsersId { get; set; }
    public Users Users { get; set; }
}

//explicitly named foreign key which is named differently from 
//convention so needs to be pointed at.  note nameof() operator
//which will give a compiler error should you rename it, so is
//better than a magic string
public class Sims
{
    public int ID { get; set; }

    [ForeignKey(nameof(Users))]
    public int MyUsersFkField { get; set; }        
    public Users Users { get; set; }
}

You can also add the attribute to the Users property and point it at the Id field.

An important note is that if you use a non-conventionally named FK property and don't specify the foreign key at all, then EF will create a FK UsersId Field in the underlying database and use that (but this won't be exposed in your model)

1
1/16/2019 11:08:12 AM

Popular Answer

The [ForeignKey] attribute overrides the default convention for a foreign key. It allows us to specify the foreign key property in the dependent entity whose name does not match with the primary key property of the principal entity.

In your case this will create the foreign key column named Users_ID in the Sims table, preventing the generation of a ID column in the database.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow